Skip to content

The Browser as a Store

The Course
•
15 min study

Your own store isn't the only external store. The browser has plenty: whether the network is up, the screen width, the system's colour scheme, the page's visibility. Each has a current value and an event that says it changed, which is exactly the shape useSyncExternalStore expects.

Online status and the colour scheme React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import { useMediaQuery, useOnlineStatus } from "./hooks.js"; export default function App() { const online = useOnlineStatus(); const prefersDark = useMediaQuery("(prefers-color-scheme: dark)"); const [minutes, setMinutes] = useState(0); return ( <main style={prefersDark ? { background: "#16232d", color: "#e5ebf2", padding: "1rem" } : { padding: "1rem" }}> <h1>Study Hub</h1> <p>{online ? "Online: your sessions are being saved." : "Offline: sessions will be saved when you reconnect."}</p> <p className="muted">Theme: {prefersDark ? "dark" : "light"}, following your system.</p> <p>Studied today: {minutes} minutes</p> <button onClick={() => setMinutes(minutes + 5)}>Log 5 minutes</button> </main> ); } import { useSyncExternalStore } from "react"; // The browser is an external store too: subscribe to its events, read its value. function subscribeOnline(callback) { window.addEventListener("online", callback); window.addEventListener("offline", callback); return () => { window.removeEventListener("online", callback); window.removeEventListener("offline", callback); }; } export function useOnlineStatus() { return useSyncExternalStore(subscribeOnline, () => navigator.onLine); } export function useMediaQuery(query) { return useSyncExternalStore( (callback) => { console.log("subscribed to", query); const list = window.matchMedia(query); list.addEventListener("change", callback); return () => list.removeEventListener("change", callback); }, () => window.matchMedia(query).matches ); } 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.

Online status

JavaScript
function subscribeOnline(callback) {
  window.addEventListener("online", callback);
  window.addEventListener("offline", callback);
  return () => {
    window.removeEventListener("online", callback);
    window.removeEventListener("offline", callback);
  };
}

export function useOnlineStatus() {
  return useSyncExternalStore(subscribeOnline, () => navigator.onLine);
}

The subscribe function is defined outside the hook, so it's the same function on every render. If it were a new function each time, React would unsubscribe and subscribe again on every render.

To try it, open your browser's developer tools, find Network, and switch to Offline. The message changes straight away. Switch back to No throttling.

navigator.onLine reports the browser's idea of network connectivity; it doesn't prove your server is reachable. Keep handling request failures even when the label says Online.

Media queries

useMediaQuery follows any CSS media query with window.matchMedia. Change your system between light and dark mode, or use the developer tools' Rendering panel to emulate prefers-color-scheme: dark, and the lab changes theme:

JavaScript
export function useMediaQuery(query) {
  return useSyncExternalStore(
    (callback) => {
      console.log("subscribed to", query);
      const list = window.matchMedia(query);
      list.addEventListener("change", callback);
      return () => list.removeEventListener("change", callback);
    },
    () => window.matchMedia(query).matches
  );
}

Use this for behaviour that JavaScript must decide: which component to render, how many items to load. For styling alone, plain CSS media queries are simpler.

Predict: does this break the rule?

Look at the subscribe function passed to useSyncExternalStore in useMediaQuery. The lab logs subscribed to each time React calls it. Press Log 5 minutes three times. What does the console show?

Check your prediction

subscribed to (prefers-color-scheme: dark) after every click. The subscribe function is an arrow function written inside the hook, so each render makes a new one, and React unsubscribes from the old function and subscribes with the new one. It's exactly what the online example avoided.

Here it costs little: one matchMedia call and one listener per render. In a component that re-renders on every keystroke, or with a subscription that's expensive to set up (a socket, a server push), it matters. The exercise fixes it without losing the query parameter.

Compared with an effect

You could write useOnlineStatus with useState and an effect that adds the listeners. You can initialize state from navigator.onLine, but you still need to handle a change between rendering and subscribing. useSyncExternalStore manages that subscription consistency for you.

These are browser-only labs. Server rendering also needs a getServerSnapshot argument and a value that matches the first client render; window and navigator aren't available on the server.

Exercise

Subscribe once per query

Change useMediaQuery so that Log 5 minutes logs nothing: the hook subscribes once when the component appears, and again only if its query changes. subscribeOnline could move outside the hook because it needs nothing from it. This subscribe function needs query, so it can't.

Then use it a second time in App: show Wide layout or Narrow layout under the theme line with useMediaQuery("(min-width: 600px)"), and check that the console shows one subscribed to line per query at the start, and none after clicking.

Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import { useMediaQuery, useOnlineStatus } from "./hooks.js"; export default function App() { const online = useOnlineStatus(); const prefersDark = useMediaQuery("(prefers-color-scheme: dark)"); const [minutes, setMinutes] = useState(0); return ( <main style={prefersDark ? { background: "#16232d", color: "#e5ebf2", padding: "1rem" } : { padding: "1rem" }}> <h1>Study Hub</h1> <p>{online ? "Online: your sessions are being saved." : "Offline: sessions will be saved when you reconnect."}</p> <p className="muted">Theme: {prefersDark ? "dark" : "light"}, following your system.</p> <p>Studied today: {minutes} minutes</p> <button onClick={() => setMinutes(minutes + 5)}>Log 5 minutes</button> </main> ); } import { useSyncExternalStore } from "react"; // The browser is an external store too: subscribe to its events, read its value. function subscribeOnline(callback) { window.addEventListener("online", callback); window.addEventListener("offline", callback); return () => { window.removeEventListener("online", callback); window.removeEventListener("offline", callback); }; } export function useOnlineStatus() { return useSyncExternalStore(subscribeOnline, () => navigator.onLine); } export function useMediaQuery(query) { return useSyncExternalStore( (callback) => { console.log("subscribed to", query); const list = window.matchMedia(query); list.addEventListener("change", callback); return () => list.removeEventListener("change", callback); }, () => window.matchMedia(query).matches ); } 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

React compares the subscribe function with the last render's using Object.is. You need the same function object on every render, until query changes. On Intermediate Day 6 you met a hook that does exactly that for functions.

Hint 2: a first step

Give the subscribe function a name inside the hook, const subscribe = ..., and pass subscribe to useSyncExternalStore. Nothing changes yet: the click still logs. Now wrap that function so React keeps it between renders, and decide what goes in its dependency list.

Show one solution
JavaScript
export function useMediaQuery(query) {
  const subscribe = useCallback((callback) => {
    console.log("subscribed to", query);
    const list = window.matchMedia(query);
    list.addEventListener("change", callback);
    return () => list.removeEventListener("change", callback);
  }, [query]);
  return useSyncExternalStore(subscribe, () => window.matchMedia(query).matches);
}

Import useCallback from "react". query is the dependency: a different query needs a different listener. The snapshot function can stay inline: React calls it to read the value but doesn't resubscribe when it changes.

JavaScript
const wide = useMediaQuery("(min-width: 600px)");
JSX
<p className="muted">{wide ? "Wide layout" : "Narrow layout"}</p>

Was this article helpful?

Your response is saved on this device.