0
0
Astroframework~30 mins

Sharing state between framework islands in Astro - Mini Project: Build & Apply

Choose your learning style9 modes available
Sharing State Between Framework Islands in Astro
📖 Scenario: You are building a simple Astro page that uses two different framework islands: one in React and one in Vue. Both islands need to share a piece of state: a counter that can be incremented from either island and stays in sync.This is like having two friends in different rooms who want to keep track of the same score on a game. They need a way to share the score so both see the same number.
🎯 Goal: Create an Astro page with a shared count state. Build a React island and a Vue island that both display the count and have a button to increment it. When you click the button in either island, the count updates in both islands.
📋 What You'll Learn
Create a shared state variable called count initialized to 0 in Astro.
Create a React island component that receives count and an increment function as props.
Create a Vue island component that receives count and an increment function as props.
Render both islands in the Astro page and share the count and increment function between them.
💡 Why This Matters
🌍 Real World
Many modern websites use multiple JavaScript frameworks together. Sharing state between these framework islands lets you build rich interactive pages without rewriting everything in one framework.
💼 Career
Understanding how to share state between different UI frameworks is valuable for frontend developers working with Astro or micro-frontend architectures.
Progress0 / 4 steps
1
Set up shared state in Astro
In your Astro page, create a variable called count and set it to 0. Also create a function called increment that increases count by 1.
Astro
Hint

Use let count = 0; to create the count variable. Then write a function increment() that adds 1 to count.

2
Create the React island component
Create a React functional component called CounterReact that accepts count and increment as props. It should render the current count and a button that calls increment when clicked.
Astro
Hint

Write a React function component that takes count and increment as props. Render a paragraph showing the count and a button that calls increment on click.

3
Create the Vue island component
Create a Vue component called CounterVue using the <script setup> syntax. It should accept count and increment as props. Render the current count and a button that calls increment when clicked.
Astro
Hint

Use <script setup> with defineProps to accept count and increment. Render the count and a button that calls increment on click.

4
Render both islands in Astro and share state
In your Astro page, import CounterReact and CounterVue. Render both components as islands, passing the shared count and increment function as props to each. Use client:load directive for hydration.
Astro
Hint

Import both components. Render them with client:load and pass count and increment as props.