React: From Components to Production · Sharing State and Structuring Apps

Custom Hooks

Extract reusable stateful logic into hooks.

A custom hook is a function starting with use that calls other hooks. It shares logic, not state — each component calling it gets its own state. Good candidates: debounced values, media queries, local storage sync, data fetching wrappers and form helpers. Follow the Rules of Hooks: call hooks at the top level, never conditionally.

import { useEffect, useState } from "react";

export function useDebouncedValue<T>(value: T, delay = 300): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);
  }, [value, delay]);
  return debounced;
}

export function useLocalStorage<T>(key: string, initial: T) {
  const [value, setValue] = useState<T>(() => {
    try { const raw = localStorage.getItem(key); return raw ? (JSON.parse(raw) as T) : initial; } catch { return initial; }
  });
  useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(value)); } catch { /* storage unavailable */ }
  }, [key, value]);
  return [value, setValue] as const;
}

// const debouncedQuery = useDebouncedValue(query); useQuery({ queryKey: ["search", debouncedQuery], ... })

Common pitfalls

  • Expecting two components using the same hook to share state.
  • Calling hooks inside conditions or loops.
  • Hooks that do too much and return large unrelated objects.

Key points

  • Hooks share logic, not state
  • Rules of Hooks apply
  • Name with the use prefix

Further reading: react.dev: Custom hooks

Practice questions

If two components call useCounter(), do they share the count?

Answer

No. Each call has its own state. To share state, lift it up, use context, or an external store.

Why can't hooks be called conditionally?

Answer

React identifies hook state by call order on each render; conditional calls would shift the order and mismatch state between renders.

Open in the app to mark lessons complete, take notes and track your progress.