React hook for managing state synchronized with localStorage
Quick Answer
useLocalStorage is a drop-in replacement for useState that persists the value in localStorage. It initialises from stored data on mount and keeps storage in sync on every update, surviving page refreshes without any extra code.
1import { useState, useEffect } from 'react';
2
3function useLocalStorage<T>(key: string, initialValue: T) {
4 const [storedValue, setStoredValue] = useState<T>(() => {
5 try {
6 const item = window.localStorage.getItem(key);
7 return item ? JSON.parse(item) : initialValue;
8 } catch (error) {
9 return initialValue;
10 }
11 });
12
13 const setValue = (value: T | ((val: T) => T)) => {
14 try {
15 const valueToStore = value instanceof Function ? value(storedValue) : value;
16 setStoredValue(valueToStore);
17 window.localStorage.setItem(key, JSON.stringify(valueToStore));
18 } catch (error) {
19 console.log(error);
20 }
21 };
22
23 return [storedValue, setValue] as const;
24}This custom React hook wraps useState and keeps it in sync with localStorage automatically. It initializes from stored data on mount and persists every update, making it easy to build features like theme preferences, saved filters, or remembered form values that survive page refreshes.
Add a typeof window !== 'undefined' guard inside the lazy initializer, or conditionally call the hook only on the client.
It is identical in API but automatically persists the value to localStorage so it survives page refreshes and tab closures.
Not automatically, but you can add a storage event listener to the window to pick up changes made in other tabs.
This free typescript code snippet for uselocalstorage hook is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement uselocalstorage hook quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.