Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React useId and useSyncExternalStore: SSR-Safe Hydration and External Stores

Generated ids that match on both sides of hydration, and external store reads that never tear and never loop.

~4 min readReact
#React#SSR#Hooks
3D illustration of deterministic SSR hydration id trees synced with tear-free external store snapshots

Quick Summary

Two hooks solve the same category of problem from opposite ends: keeping client state identical to what the server produced. useId generates identifiers that match between a server render and its hydration pass, so aria-describedby, htmlFor, and id attributes do not break when the markup is streamed and rehydrated. useSyncExternalStore reads a value that lives outside React — matchMedia, localStorage, a WebSocket, a Redux store — in a way that never tears and that has a defined value during server rendering.

Both exist because hydration is a comparison. The client does not build the page from scratch; it adopts server HTML and attaches behaviour. Any value that differs between the two passes is a mismatch, and anything random, time-based, or environment-based in the render path differs by construction. useId removes one source of that difference. useSyncExternalStore removes another, by letting you supply a separate server snapshot instead of reading window during render.

The failure modes are quiet. useId returns a value that depends on the tree path rather than on call order, so it stays stable when a component is reused, but it changes when the tree structure changes — it is not a cache key, not a list key, and not something to parse. useSyncExternalStore will loop forever if getSnapshot returns a new object on every call, because React compares snapshots with Object.is to decide whether a re-render is needed.

Basic Syntax & Signature

tsx
import { useId, useSyncExternalStore } from "react"; function Field({ label }: { label: string }) { const id = useId(); return ( <div> <label htmlFor={id}>{label}</label> <input id={id} aria-describedby={`${id}-hint`} /> <p id={`${id}-hint`}>Required, 8 characters minimum.</p> </div> ); } // subscribe: called with a callback, returns an unsubscribe function. // getSnapshot: must return a cached, immutable value. // getServerSnapshot: used during hydration and server rendering. const isOnline = useSyncExternalStore( (callback) => { window.addEventListener("online", callback); window.addEventListener("offline", callback); return () => { window.removeEventListener("online", callback); window.removeEventListener("offline", callback); }; }, () => navigator.onLine, () => true );

Both subscribe and snapshot functions must be stable across renders, or the store is torn down and re-subscribed on every commit:

tsx
// Defined once at module scope: identity never changes. function subscribeToWidth(callback: () => void) { const mql = window.matchMedia("(max-width: 768px)"); mql.addEventListener("change", callback); return () => mql.removeEventListener("change", callback); } const getWidthSnapshot = () => window.matchMedia("(max-width: 768px)").matches; const getServerWidthSnapshot = () => false; function useIsMobile() { return useSyncExternalStore(subscribeToWidth, getWidthSnapshot, getServerWidthSnapshot); }

For multiple independent apps on one page, createRoot(container, { identifierPrefix }) and hydrateRoot(..., { identifierPrefix }) namespace every useId value so two roots never collide.

Key Comparison Table

AspectuseIduseSyncExternalStore
Problem solvedUnique, hydration-stable idsTear-free reads from external state
Server supportGenerates ids on both passesRequires getServerSnapshot
Depends on tree positionYesNo
Changes between rendersNo, while mountedWhenever the snapshot changes
Valid as a list keyNoNot applicable
Valid as a cache keyNoNot applicable
Mismatch when tree differsYes, ids differ on hydrationYes, if snapshots differ
Stable function requirementsNonesubscribe and getSnapshot identity
Re-render triggerNeverSnapshot changes by Object.is
Typical misuseParsing or truncating the idInline arrow functions, fresh objects

Practical Edge Cases & Deep Dives

1. Ids inside a repeated component

tsx
function AccordionItem({ title, children }: { title: string; children: React.ReactNode }) { const id = useId(); const [open, setOpen] = useState(false); return ( <div> <button aria-expanded={open} aria-controls={`${id}-panel`} onClick={() => setOpen(!open)}> {title} </button> <div id={`${id}-panel`} hidden={!open}> {children} </div> </div> ); }

Three accordion items on a page produce three different ids without a counter, without a useRef, and without any risk of a hydration mismatch. A module-level counter would also produce unique values in a single pass, but not necessarily in the same order on the server and on the client — which is exactly the case useId is built to survive.

2. Using a generated id in a selector

tsx
function Anchored() { const id = useId(); const ref = useRef<HTMLDivElement>(null); useLayoutEffect(() => { // Ids may contain characters that are not valid unescaped in a selector. const el = document.querySelector(CSS.escape(`#${id}`)); if (el) ref.current?.scrollIntoView(); }, [id]); return <div id={id} ref={ref}>anchored</div>; }

Prefer the ref. When a selector is unavoidable, CSS.escape is the difference between working and a SyntaxError from querySelector, because generated ids are not guaranteed to be plain alphanumerics and React has changed the format between versions. Code that strips colons or assumes a prefix breaks on upgrade.

3. A store with a selector, without tearing

tsx
type State = { count: number; name: string }; let state: State = { count: 0, name: "anon" }; const listeners = new Set<() => void>(); const store = { getState: () => state, setState(next: Partial<State>) { state = { ...state, ...next }; listeners.forEach((l) => l()); }, subscribe(listener: () => void) { listeners.add(listener); return () => listeners.delete(listener); }, }; function useCount() { return useSyncExternalStore( store.subscribe, () => store.getState().count, () => 0 ); } function useName() { return useSyncExternalStore( store.subscribe, () => store.getState().name, () => "anon" ); }

Each selector subscribes to the whole store but only re-renders when its own snapshot changes, because React compares the returned value, not the store object. The getServerSnapshot values must match what the server rendered; returning undefined there and 0 on the client produces a mismatch warning on the first commit.

4. Reading localStorage without a hydration mismatch

jsx
function useLocalStorageValue(key, fallback) { const subscribe = useCallback( (callback) => { const onStorage = (e) => { if (e.key === key || e.key === null) callback(); }; window.addEventListener("storage", onStorage); return () => window.removeEventListener("storage", onStorage); }, [key] ); const getSnapshot = useCallback(() => window.localStorage.getItem(key), [key]); // The server has no storage: render the fallback there, then hydrate. const getServerSnapshot = useCallback(() => null, []); const raw = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); return raw === null ? fallback : JSON.parse(raw); }

localStorage.getItem returns a string, so the snapshot is a primitive and the identity check works. Returning JSON.parse(...) straight from getSnapshot would create a new object on every call and trigger an infinite render loop — parse outside the snapshot, one layer up.

5. The infinite loop from an uncached snapshot

tsx
// Wrong: new object every call, Object.is never matches, React re-renders forever. function useBadState() { return useSyncExternalStore( subscribeToResize, () => ({ width: window.innerWidth, height: window.innerHeight }) ); } // Right: cache the object and only replace it when the numbers change. let cached = { width: 0, height: 0 }; function readSize() { const width = window.innerWidth; const height = window.innerHeight; if (cached.width !== width || cached.height !== height) cached = { width, height }; return cached; } function useSize() { return useSyncExternalStore(subscribeToResize, readSize, () => ({ width: 0, height: 0 })); }

React logs a warning ("The result of getSnapshot should be cached") before it locks up, so the message is worth taking literally. The same rule applies to useSelector in Redux Toolkit and to useStore in Zustand, both of which are built on this hook.

6. Ids and the identifierPrefix for micro-frontends

tsx
import { createRoot, hydrateRoot } from "react-dom/client"; const container = document.getElementById("widget")!; if (container.hasChildNodes()) { hydrateRoot(container, <Widget />, { identifierPrefix: "widget-" }); } else { createRoot(container, { identifierPrefix: "widget-" }).render(<Widget />); }

Two React roots on one page each count ids from their own root, so without prefixes both produce the same strings and the second one wins in the DOM. identifierPrefix is applied consistently to server output and client hydration, which is why it belongs in the bootstrap file rather than in every component.

Common Compilation/Runtime Mistakes

SymptomCauseFix
Duplicate id attributes in the pageStatic string used in a repeated componentuseId per instance
Hydration mismatch on id/aria-describedbyRandom or counter-based iduseId, or identifierPrefix for multiple roots
querySelector throws on a generated idUnescaped special charactersCSS.escape or a ref
Ids reused across two rootsSeparate roots, no prefixidentifierPrefix on both
useId used as a list keyMisunderstanding of stabilityKey from data
"The result of getSnapshot should be cached"New object from getSnapshotCache and return the same reference
Store re-subscribes on every renderInline subscribe arrowModule-level function or useCallback
Hydration mismatch on store-backed UIgetServerSnapshot omittedPass a server-safe value
Immediate re-render loopSnapshot changes on every readDerive from a primitive
useSyncExternalStore in an async Server ComponentNot allowed; it is a client hookMove it into a client component

The shared principle is that the server and the client must agree on what they render before hydration, and that React's comparison is shallow and synchronous. useId guarantees agreement for identifiers; useSyncExternalStore lets you declare the server's answer for values the server cannot read, and then converge after hydration without tearing a render in half.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.