useLocalStorage hook
A state hook that mirrors its value into localStorage, with safe hydration and cross-tab synchronization.
- #react
- #hooks
- #persistence
Keeps a piece of React state in localStorage so it survives a reload, and stays safe to render on the server.
Overview
Reading window.localStorage during the first render breaks server rendering and causes a hydration mismatch. This version reads in an effect instead, and keeps a lazy initializer for the client-only case.
Implementation
The implementation sits beside this guide in use-local-storage.ts:
Cross-tab synchronization
The storage event fires in every other tab of the same origin, which makes it a cheap synchronization channel:
Caveats
- A value must be JSON-serializable.
DateandMapneed a custom reviver. - A write is synchronous and blocks the main thread, so keep payloads small.
- A private browsing window may throw on a write even when reads succeed.
Related entries
- useEventListener hook. The subscription pattern underneath the
storagelistener. - Reducer store. Persists a whole store slice instead of one value.
Files in this entry
Saved beside the document, and served as-is.
Related entries
useEventListener hook
Attach a DOM event listener once and keep the handler current, so a changing callback never detaches the listener.
useMediaQuery hook
Subscribe to a CSS media query from React, without a resize listener or a layout read.
useIntersectionObserver hook
Track element visibility for lazy loading, infinite scroll and scroll-spy navigation.