All tutorials
    React

    Building Reusable Custom React Hooks

    Extract stateful logic into composable hooks that keep your components clean.

    8 min readMay 28, 2026

    Why Custom Hooks?

    Custom hooks let you share logic across components without wrapper hell. Any function that starts with 'use' and calls other hooks is a custom hook.

    A useLocalStorage Hook

    This hook syncs a piece of state with localStorage so it survives page reloads.

    React
    function useLocalStorage(key, initial) {
      const [value, setValue] = useState(() => {
        const stored = localStorage.getItem(key);
        return stored ? JSON.parse(stored) : initial;
      });
    
      useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
      }, [key, value]);
    
      return [value, setValue];
    }