Home About Skills Products Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Tutorials · React JS

Building Custom Hooks

Building Custom Hooks

When the same stateful logic (like tracking window size, or syncing with localStorage) repeats across two or more components, you can extract it into a custom hook — just write a new function whose name starts with use, and call other hooks inside it.

Rules of Hooks (Important)

  • Only call hooks at the top level of a React function component, or inside another custom hook.
  • Never call a hook inside a loop, condition, or nested function.
  • A custom hook's name must always start with use (like useLocalStorage) — this is how React and its tooling recognize it and apply the rules correctly.

Example: A useLocalStorage Hook

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

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

  return [value, setValue];
}

Using It in Any Component

function SettingsPage() {
  const [darkMode, setDarkMode] = useLocalStorage('darkMode', false);

  return (
    <label>
      <input
        type="checkbox"
        checked={darkMode}
        onChange={(e) => setDarkMode(e.target.checked)}
      />
      Dark Mode
    </label>
  );
}

From the outside, useLocalStorage behaves exactly like useState — the logic behind it (reading/writing localStorage) is hidden away, and can now be reused in any component with a single line.

Key Takeaways

  • A custom hook is a function whose name starts with use... and that calls React hooks internally.
  • Extracting repeated stateful logic into a custom hook keeps your code DRY.
  • Custom hooks follow the same rules as built-in hooks (call them only at the top level).
What is React? JSX Introduction and Your First Component

What is React? JSX Introduction and Your First Component

What problem React actually solves, how JSX syntax works, and how to build your first component.

Setting Up a React App with Vite

Setting Up a React App with Vite

Set up a modern React project in seconds with Vite, and understand the resulting folder structure.

Understanding Components and Props

Understanding Components and Props

Build functional components and pass data from parent to child components using props.

Esc