Lesson 13 of 20

Custom Hooks

Creating Reusable Hooks

Custom hooks let you extract component logic into reusable functions. A custom hook is simply a function that starts with 'use' and can call other hooks. They let you share stateful logic between components without duplicating code.

Custom hooks follow the same rules as built-in hooks: they must be called at the top level and only from React functions.

Example
// Custom hook: useLocalStorage
function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const saved = localStorage.getItem(key);
    return saved ? JSON.parse(saved) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

// Custom hook: useToggle
function useToggle(initial = false) {
  const [value, setValue] = useState(initial);
  const toggle = () => setValue(prev => !prev);
  return [value, toggle];
}

// Using custom hooks
function Settings() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');
  const [showSidebar, toggleSidebar] = useToggle(true);

  return (
    <div>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
        Theme: {theme}
      </button>
      <button onClick={toggleSidebar}>
        {showSidebar ? 'Hide' : 'Show'} Sidebar
      </button>
    </div>
  );
}
  • Custom hooks must start with 'use' (useLocalStorage, useFetch, etc.)
  • They can use useState, useEffect, useRef, and other hooks
  • Each component using a custom hook gets its own independent state
  • Extract repeated logic patterns into custom hooks
  • Custom hooks can return values, arrays, objects, or functions
Notes
  • Custom hooks are the primary mechanism for code reuse in React. If you find yourself copying the same useState + useEffect pattern across components, extract it into a custom hook.