Skip to content
jshacks.dev
Frameworks

Write a custom hook for local storage

Wrap useState and localStorage in a reusable useLocalStorage hook, with a lazy initializer and a safe fallback when storage is unavailable.

1 min read
Summarize in AI

Several components need a value that survives a refresh. A custom hook puts the read and write in one place and behaves like useState.

src/useLocalStorage.jsJSX
import { useEffect, useState } from 'react';

export function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    try {
      const stored = localStorage.getItem(key);
      return stored === null ? initialValue : JSON.parse(stored);
    } catch {
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      localStorage.setItem(key, JSON.stringify(value));
    } catch {
      // storage is full or blocked, keep the in-memory value
    }
  }, [key, value]);

  return [value, setValue];
}
src/Theme.jsxJSX
import { useLocalStorage } from './useLocalStorage.js';

export function Theme() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');
  return <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>{theme}</button>;
}
Text
light     (first visit)
dark      (after a click, and still dark after a reload)

Passing a function to useState runs it only on the first render, so storage is not read again every time. Both calls sit in try because Safari private mode and some embedded browsers throw on access.

On a server-rendered page, localStorage does not exist during render, so read it in an effect or guard with typeof window. Otherwise the first client render differs from the server HTML.

Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.