Custom Hook Patterns: useDebounce, useLocalStorage, usePrevious, and More

Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.

1

Exercise 1 of 1

Custom Hook Patterns Quiz

Three common custom hooks with bugs. Spot SSR safety issues, understand the debounce pattern with cleanup, and identify the missing race condition fix.

1
function useWindowSize() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    const update = () => setSize({
      width: window.innerWidth,
      height: window.innerHeight,
    });
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, []);

  return size;
}

What problem does this hook have in a Next.js SSR app?

2
function useDebounce(value, delay) {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);
  }, [value, delay]);

  return debounced;
}

What does this hook do when "value" changes rapidly?

3
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    setLoading(true);
    fetch(url)
      .then(r => r.json())
      .then(d => { setData(d); setLoading(false); })
      .catch(e => { setError(e); setLoading(false); });
  }, [url]);

  return { data, loading, error };
}

What critical problem does this hook have?

0/3 answered

💡 Custom hooks are just functions. They can introduce all the same bugs as regular hook usage — SSR safety, missing cleanup, race conditions. The same patterns that fix these in components fix them in custom hooks.

Practice: Custom Hook Patterns: useDebounce, useLocalStorage, usePrevious, and More — Interactive Exercises | Durgesh Rai