Skip to content

External Stores

The Course
•
20 min study

State that doesn't belong to a component

Context with a reducer, from the intermediate course, keeps shared state inside React: a provider component owns it. Sometimes state needs to live outside any component:

  • code that isn't React needs it too, such as a module that saves changes to a server or a timer that keeps running;
  • several React roots, or a page that's partly React, share it;
  • many components each need a different small part of it, and shouldn't all re-render when any part changes.

An external store is one way to meet those needs. Libraries such as Redux and Zustand offer store integrations built around React's subscription APIs; other libraries use different designs. Here you'll build a small store and connect it with useSyncExternalStore.

A store outside React React · 7 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import "./autoSave.js"; import { logSession, sessionStore } from "./session.js"; import { useStore } from "./useStore.js"; function Header() { const { sessions, minutes } = useStore(sessionStore); return <p className="muted">{sessions} sessions · {minutes} minutes today</p>; } function LogButtons() { return ( <div className="toolbar"> <button onClick={() => logSession(25)}>Log 25 minutes</button> <button onClick={() => logSession(50)}>Log 50 minutes</button> </div> ); } export default function App() { return ( <main> <h1>Study Hub</h1> <Header /> <section className="panel"> <LogButtons /> </section> </main> ); } import { sessionStore } from "./session.js"; // Not React: a plain module that reacts to store changes, like code that // would save to a server or to localStorage. sessionStore.subscribe(() => { const { minutes, sessions } = sessionStore.getState(); console.log(`saved: ${sessions} sessions, ${minutes} minutes`); }); import { createStore } from "./store.js"; export const sessionStore = createStore({ minutes: 0, sessions: 0, topic: "Reducers" }); export function logSession(minutes) { sessionStore.setState((s) => ({ ...s, minutes: s.minutes + minutes, sessions: s.sessions + 1 })); } export function setTopic(topic) { sessionStore.setState((s) => ({ ...s, topic })); } // A tiny store: state that lives outside React. Any code can read it, change // it, or subscribe to changes, including code that isn't a component. export function createStore(initialState) { let state = initialState; const listeners = new Set(); return { getState: () => state, setState(update) { const next = typeof update === "function" ? update(state) : update; if (Object.is(next, state)) return; state = next; listeners.forEach((listener) => listener()); }, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, }; } import { useSyncExternalStore } from "react"; // Re-renders the component when the store changes. export function useStore(store) { return useSyncExternalStore(store.subscribe, store.getState); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Press Log 25 minutes twice and watch the console.

The store

createStore returns three functions:

  • getState() returns the current state.
  • setState(update) replaces it, with a value or an updater function, then calls every listener. If nothing changed, it does nothing.
  • subscribe(listener) adds a listener, and returns a function that removes it:
JavaScript
export function createStore(initialState) {
  let state = initialState;
  const listeners = new Set();

  return {
    getState: () => state,
    setState(update) {
      const next = typeof update === "function" ? update(state) : update;
      if (Object.is(next, state)) return;
      state = next;
      listeners.forEach((listener) => listener());
    },
    subscribe(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
  };
}

It's ordinary JavaScript. session.js creates one store and two functions that change it. autoSave.js subscribes without any React, and logs saved: … each time, as a real app might save to a server:

JavaScript
sessionStore.subscribe(() => {
  const { minutes, sessions } = sessionStore.getState();
  console.log(`saved: ${sessions} sessions, ${minutes} minutes`);
});

useSyncExternalStore

JavaScript
export function useStore(store) {
  return useSyncExternalStore(store.subscribe, store.getState);
}

React calls subscribe when the component mounts, with a callback that re-renders the component, and calls the function it returns when the component unmounts. Each render reads the current value with getState.

You could do this with useState and useEffect, but useSyncExternalStore also handles the hard cases: a store that changes during a render, or during a transition. With it, every component on the screen sees the same value at the same time.

Predict

LogButtons doesn't call useStore. Does it re-render when you log a session?

Check your prediction

No. Only components that call useStore subscribe. LogButtons just calls logSession, a plain function, so it never needs to re-render. With context, every consumer re-renders for any change; a store lets each component choose. The next lesson takes that further.

Exercise

Reset from outside React

Add a resetDay() function to session.js that sets minutes and sessions back to 0. Call it from autoSave.js when the total passes 100 minutes, logging daily limit reached, starting over. The header should update by itself.

Your working space React · 7 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import "./autoSave.js"; import { logSession, sessionStore } from "./session.js"; import { useStore } from "./useStore.js"; function Header() { const { sessions, minutes } = useStore(sessionStore); return <p className="muted">{sessions} sessions · {minutes} minutes today</p>; } function LogButtons() { return ( <div className="toolbar"> <button onClick={() => logSession(25)}>Log 25 minutes</button> <button onClick={() => logSession(50)}>Log 50 minutes</button> </div> ); } export default function App() { return ( <main> <h1>Study Hub</h1> <Header /> <section className="panel"> <LogButtons /> </section> </main> ); } import { sessionStore } from "./session.js"; // Not React: a plain module that reacts to store changes, like code that // would save to a server or to localStorage. sessionStore.subscribe(() => { const { minutes, sessions } = sessionStore.getState(); console.log(`saved: ${sessions} sessions, ${minutes} minutes`); }); import { createStore } from "./store.js"; export const sessionStore = createStore({ minutes: 0, sessions: 0, topic: "Reducers" }); export function logSession(minutes) { sessionStore.setState((s) => ({ ...s, minutes: s.minutes + minutes, sessions: s.sessions + 1 })); } export function setTopic(topic) { sessionStore.setState((s) => ({ ...s, topic })); } // A tiny store: state that lives outside React. Any code can read it, change // it, or subscribe to changes, including code that isn't a component. export function createStore(initialState) { let state = initialState; const listeners = new Set(); return { getState: () => state, setState(update) { const next = typeof update === "function" ? update(state) : update; if (Object.is(next, state)) return; state = next; listeners.forEach((listener) => listener()); }, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, }; } import { useSyncExternalStore } from "react"; // Re-renders the component when the store changes. export function useStore(store) { return useSyncExternalStore(store.subscribe, store.getState); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Code outside React changes the store the same way React code does: through the store's own update function. Every subscriber, including the components reading it through useSyncExternalStore, hears about the change, so nothing in the header needs touching. Watch out for the store's other fields.

Hint 2: a first step

Write resetDay first, then call it from the subscribe callback in autoSave.js, after the log line, behind a check on the total. Log 50 minutes three times. Setting state from a listener runs the listeners again, so you'll see a second saved: line straight after the reset. Why doesn't your check make it loop forever?

Show one solution

In session.js:

JavaScript
export function resetDay() {
  sessionStore.setState((s) => ({ ...s, minutes: 0, sessions: 0 }));
}

In autoSave.js:

JavaScript
import { resetDay, sessionStore } from "./session.js";

sessionStore.subscribe(() => {
  const { minutes, sessions } = sessionStore.getState();
  console.log(`saved: ${sessions} sessions, ${minutes} minutes`);
  if (minutes > 100) {
    console.log("daily limit reached, starting over");
    resetDay();
  }
});

Logging 50 minutes three times reaches 150, logs the reset, and the header goes back to 0 sessions · 0 minutes today.

Was this article helpful?

Your response is saved on this device.