A localStorage hook with useSyncExternalStore
Use useSyncExternalStore to share a localStorage value across components and render a fallback on the server.
Two components read the theme from localStorage, one of them writes a new value, and the other keeps showing the old one until you reload. Use useSyncExternalStore to notify the other component and read a fallback when rendering on the server.
import { useCallback, useSyncExternalStore } from 'react'
const listeners = new Set()
function subscribe(callback) {
listeners.add(callback)
window.addEventListener('storage', callback)
return () => {
listeners.delete(callback)
window.removeEventListener('storage', callback)
}
}
export function useLocalStorage(key, fallback) {
const raw = useSyncExternalStore(
subscribe,
() => window.localStorage.getItem(key),
() => null,
)
const set = useCallback((next) => {
window.localStorage.setItem(key, JSON.stringify(next))
listeners.forEach((callback) => callback())
}, [key])
const value = raw === null ? fallback : JSON.parse(raw)
return [value, set]
}Call the hook with the same key and fallback in each component. This example expects JSON-serializable values, valid JSON in storage and access to localStorage. Decide how your app should handle a blocked read, quota errors or invalid stored data.
Notify both kinds of writers
subscribe gets a callback from React and calls it whenever the store changes. The storage event covers changes from other tabs on the same origin. For writes in this tab, use the hook's setter so it can notify subscribers.
The third argument, getServerSnapshot, runs during server rendering and hydration. It returns null, so both the server and the initial hydration render use the fallback. React can read the actual stored value after hydration.
Return a value React can compare
React compares consecutive getSnapshot results with Object.is. Return the same value until the store changes. A fresh object fails that comparison on each read.
() => ({ value: window.localStorage.getItem(key) })A component that reads snapshot.value with this getter can hit Maximum update depth exceeded, because each snapshot looks new to React. The hook above returns the stored string and parses it after React reads the snapshot.
Check the sharing and the server
Use two copies of a component that reads the same key and lets you change it. With no theme key, both show light. Clicking either button updates both to dark.
function ThemeButton() {
const [theme, setTheme] = useLocalStorage('theme', 'light')
return <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>{theme}</button>
}renderToString(<ThemeButton />) renders a button reading light even when browser storage holds dark. Hydrating that markup in the browser starts with light, then updates to dark when React reads the stored value.