📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials React Modern Development Custom Hooks

Custom Hooks

6 min read Quiz at the end
Custom hooks are functions starting with use that call other hooks inside. They let multiple components share stateful logic without duplicating code. Each component that calls the hook gets its own independent state.

Custom Hooks

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

  const set = (v) => {
    setValue(v);
    localStorage.setItem(key, JSON.stringify(v));
  };

  return [value, set];
}

// Usage
const [theme, setTheme] = useLocalStorage("theme", "light");
Topic Quiz · 5 questions

Test your understanding before moving on

1. Custom hooks must start with:
💡 Custom hooks must start with "use" — this is a React convention enforced by linting rules.
2. What can custom hooks contain?
💡 Custom hooks can use useState, useEffect, useContext, etc. inside them.
3. Can custom hooks be shared?
💡 Custom hooks are plain functions — easily shared across components or published as packages.
4. Why use custom hooks?
💡 Custom hooks extract reusable stateful logic from components.
5. What is the useLocalStorage hook?
💡 useLocalStorage is a popular custom hook that persists state to localStorage.