Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Components and Islands

Sharing State Between Islands

Islands hydrate separately, so they cannot share React context. Learn Nano Stores, atoms, maps, persistent state and custom events to connect islands.

Each Astro island is a separate application root. A cart button in the header and a product list in the main area might both be React components, but they are two independent React trees with no shared parent. React context, Vue provide/inject and Svelte context stop at the edge of the island, so they cannot connect two islands.

The solution is to keep shared state outside any framework, in a small module that every island imports. Because the browser loads a JavaScript module only once, every importer gets the same object.

The Nano Stores approach

Astro's documentation recommends Nano Stores: a tiny library (under 1 KB per store) with adapters for React, Preact, Vue, Svelte and Solid. You create stores in a plain file:

TypeScript
// src/stores/cart.ts
import { atom, map, computed } from "nanostores";

export const isCartOpen = atom(false);

export const cartItems = map<Record<string, { id: string; name: string; qty: number }>>({});

export const cartCount = computed(cartItems, (items) =>
  Object.values(items).reduce((sum, item) => sum + item.qty, 0),
);

export function addToCart(item: { id: string; name: string }) {
  const existing = cartItems.get()[item.id];
  cartItems.setKey(item.id, {
    ...item,
    qty: existing ? existing.qty + 1 : 1,
  });
  isCartOpen.set(true);
}

Three store types appear in that file:

  • atom holds a single value (a boolean, a string, an object that you replace).
  • map holds an object whose keys you can update individually with setKey.
  • computed derives a value from other stores and updates automatically.

Using stores in components

Each framework has a small helper package. In React you use useStore from @nanostores/react:

JSX
// src/components/CartBadge.jsx
import { useStore } from "@nanostores/react";
import { cartCount, isCartOpen } from "../stores/cart";

export default function CartBadge() {
  const count = useStore(cartCount);
  return (
    <button onClick={() => isCartOpen.set(!isCartOpen.get())}>
      Cart ({count})
    </button>
  );
}
JSX
// src/components/AddButton.jsx
import { addToCart } from "../stores/cart";

export default function AddButton({ id, name }) {
  return <button onClick={() => addToCart({ id, name })}>Add to cart</button>;
}

Both components are islands in different parts of the page. When AddButton calls addToCart, the store changes and CartBadge re-renders, even though they share no parent. Vue (@nanostores/vue) and Svelte (which can use a store directly with the $ prefix) work the same way, and you can even mix frameworks.

Islands share a store

Island A Add to cart button
Store module One shared object
1 / 2

Persisting state

Shared state vanishes on a page reload. The @nanostores/persistent package keeps an atom in localStorage and synchronizes it between tabs:

TypeScript
import { persistentAtom } from "@nanostores/persistent";

export const theme = persistentAtom<"light" | "dark">("theme", "light");

Remember that stores run in the browser. On the server a store is created fresh for each render, so do not use a store to hold per-visitor data during server rendering, because the module could be shared between requests.

Other ways to connect islands

Not every case needs a library:

  • Custom DOM events. An island dispatches window.dispatchEvent(new CustomEvent("cart:add", { detail })) and another listens for it. It works across frameworks with zero dependencies, but you must manage listeners and types yourself.
  • URL state. Use query strings or the hash for state that should be shareable or bookmarkable, such as filters.
  • Web Storage events. The storage event fires in other tabs, not the same one.
  • Lifting into a single island. If two components are always shown together, put them in one parent island and use that framework's own state tools.

Stand-in: a tiny atom store

This stand-in implements atom, computed and subscribe in about twenty lines. It shows why two separate "islands" that import the same module stay in sync.

Node.js Stand-in: atoms, computed and subscribers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stand-in: events as the other option

The event approach decouples islands even more, since neither imports the other. This stand-in models a global event bus with EventTarget, and shows its main weakness: handlers are untyped.

Node.js Stand-in: islands talking through events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Guidelines

  • Keep stores small and focused: one for the cart, one for the theme, one for a modal.
  • Export actions (functions that change a store) rather than letting every component call set directly.
  • Avoid storing huge objects; stores are great for UI state, not for datasets.
  • Do not read a store during server rendering and expect the visitor's data. State on the server is not per user.
  • Prefer sending ordinary props for data that is known at build time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can two islands not share React context?

    Context flows through a single component tree. Islands are independent trees.
  2. 2. Why do islands that import the same store module see the same state?

    JavaScript modules are singletons per page load, so shared module-level state is shared by every importer.
  3. 3. What does a computed store do?

    computed recalculates automatically from its source stores.
  4. 4. What is a downside of using plain custom events between islands?

    Nothing checks that listeners and emitters agree on names or payloads.

Summary

  • Islands are separate roots, so framework context cannot connect them.
  • Put shared state in a plain module; Nano Stores offers atom, map and computed with adapters for each framework.
  • Use persistentAtom for state that survives reloads.
  • Custom events and URL state are lightweight alternatives for simple cases.
  • Never rely on module state for per-visitor data during server rendering.

Next: Markdown Pages and Frontmatter