Share State Between Astro Components

When building an Astro website, you may need to share state across components. Astro recommends the use of Nano Stores for shared client storage.

  1. Install Nano Stores:
Terminal window
npm install nanostores
  1. Create a store. In this example, the store tracks whether a dialog is open or not:
import { atom } from 'nanostores';
export const isOpen = atom(false);
  1. Import and use the store in a <script> tag in the components that will share state.

The following Button and Dialog components each use the shared isOpen state to control whether a particular <div> is hidden or displayed:

<button id="openDialog">Open</button>
import { isOpen } from '../store.js';
// Set the store to true when the button is clicked
function openDialog() {
// Add an event listener to the button
document.getElementById('openDialog').addEventListener('click', openDialog);
<div id="dialog" style="display: hidden">Hello world!</div>
import { isOpen } from '../store.js';
// Listen to changes in the store, and show/hide the dialog accordingly
isOpen.subscribe(open => {
if (open) {
document.getElementById('dialog').style.display = 'block';
} else {
document.getElementById('dialog').style.display = 'none';
document.getElementById('openDialog').addEventListener('click', openDialog);

More recipes