Skip to main content
100%

A hook that persists useState() to localStorage.

✓ Published0🌍 Public
Aabonello
Last edited Jun 24, 2021
Created on Dec 30, 2021

This example demonstrates a custom React hook that synchronizes a component’s state with the browser’s localStorage, enabling persistent data across page reloads. The hook, `useStateStorage`, initializes state with a provided default value and reads any stored JSON from localStorage on mount, updating the state if valid. It exposes a setter function that writes both the new state and its JSON-serialized form to localStorage. The code uses React’s `useState`, `useEffect`, and `useCallback` APIs to manage lifecycle and memoization, while leveraging `localStorage.getItem` and `localStorage.setItem` for storage operations.

AI-generated description

Similar vizzes