Sharing state between framework islands helps different parts of a webpage work together smoothly. It lets components built with different tools talk to each other.
0
0
Sharing state between framework islands in Astro
Introduction
You have a button in one island that changes data shown in another island.
You want to keep user info consistent across different parts of the page.
You need to update multiple components when a user interacts with one.
You want to avoid reloading the whole page to share data.
You want to build a fast, interactive site using multiple frameworks.
Syntax
Astro
import { createSignal } from 'solid-js'; // Create a shared state signal const [state, setState] = createSignal(initialValue); // Pass state and setState as props to islands <IslandA state={state} setState={setState} /> <IslandB state={state} setState={setState} />
Use a shared state signal or store that multiple islands can access.
Pass the state and update functions as props to each island.
Examples
One island changes the count, another shows it.
Astro
// Create shared state
const [count, setCount] = createSignal(0);
// Island A increments count
<IslandA count={count} setCount={setCount} />
// Island B shows count
<IslandB count={count} />Load the island on the client to use shared state interactively.
Astro
// Using Astro's client directives
<Island client:load>
<Counter count={count} setCount={setCount} />
</Island>Sample Program
This example shows two islands sharing the same count state. Clicking the button updates the count, and the display updates automatically.
Astro
import { createSignal } from 'solid-js'; const [count, setCount] = createSignal(0); function IncrementButton({ count, setCount }) { return ( <button onClick={() => setCount(count() + 1)} aria-label="Increment count"> Increment </button> ); } function DisplayCount({ count }) { return <p>Current count: {count()}</p>; } export default function App() { return ( <main> <IncrementButton count={count} setCount={setCount} /> <DisplayCount count={count} /> </main> ); }
OutputSuccess
Important Notes
Make sure to use client directives like client:load to enable interactivity.
Passing state as props keeps islands in sync without full page reloads.
Use accessible labels like aria-label for better user experience.
Summary
Sharing state lets different islands work together smoothly.
Use shared signals and pass them as props to islands.
Client directives enable interactive updates on the page.