#Shared state
4 messages · Page 1 of 1 (latest)
Hi @regal gazelle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Svelte stores cannot be directly used in React islands. They are Svelte-specific. For sharing state between different framework islands (like React and Svelte), Astro recommends using Nano Stores instead, which are framework-agnostic.
Note: The knowledge sources explicitly state that you might prefer Nano Stores over Svelte stores if "you want to communicate between Svelte and other UI frameworks like Preact or Vue." [Why Nano Stores]
Here's how to share state between a React island and a Svelte island using Nano Stores:
1. Install Nano Stores
npm install nanostores @nanostores/react
(No helper package is needed for Svelte — Nano Stores work like standard Svelte stores.) [Installing Nano Stores]
2. Create a shared store
// src/cartStore.js
import { atom } from 'nanostores';
export const isCartOpen = atom(false);
3. Use the store in a React island
// src/components/CartFlyoutToggle.jsx (React)
import { useStore } from '@nanostores/react';
import { isCartOpen } from '../cartStore';
export default function CartButton() {
const $isCartOpen = useStore(isCartOpen);
return (
<button onClick={() => isCartOpen.set(!$isCartOpen)}>Cart</button>
);
}
4. Use the same store in a Svelte island
<!-- src/components/CartFlyout.svelte -->
<script>
import { isCartOpen } from '../cartStore';
</script>
{#if $isCartOpen}
<aside>...</aside>
{/if}