Skip to content

Custom Hooks Collection

Medium ~40 min

What you'll build

Three custom hooks: useLocalStorage (persisted state), useDebounce (debounced value), and useFetch (data fetching with loading/error states).

Goals

  • Extract reusable logic into a custom hook
  • Use useState and useEffect inside custom hooks
  • Return values and functions from a hook
  • Compose hooks inside other hooks

Prerequisites

  • React function components
  • useState and useEffect hooks
  • JavaScript closures

Steps

  1. 1

    Build useLocalStorage

    A custom hook is just a function that starts with 'use' and calls other hooks. Build useLocalStorage that works like useState but persists to localStorage.

    Code
    import { useState, useEffect } from 'react';
    
    function useLocalStorage(key, initialValue) {
      const [value, setValue] = useState(() => {
        const stored = localStorage.getItem(key);
        return stored ? JSON.parse(stored) : initialValue;
      });
      
      useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
      }, [key, value]);
      
      return [value, setValue];
    }
    
    // Usage:
    function App() {
      const [name, setName] = useLocalStorage('name', 'Guest');
      return <input value={name} onChange={e => setName(e.target.value)} />;
    }

    Expected result

    The input value persists across page reloads via localStorage.

  2. 2

    Build useDebounce

    Create a hook that returns a debounced version of a value — it only updates after the user stops typing for a delay. Useful for search inputs.

    Code
    function useDebounce(value, delay = 300) {
      const [debounced, setDebounced] = useState(value);
      
      useEffect(() => {
        const timer = setTimeout(() => setDebounced(value), delay);
        return () => clearTimeout(timer);  // cleanup on each change
      }, [value, delay]);
      
      return debounced;
    }
    
    // Usage in a search component:
    function Search() {
      const [query, setQuery] = useState('');
      const debouncedQuery = useDebounce(query, 500);
      
      useEffect(() => {
        if (debouncedQuery) console.log('Searching for:', debouncedQuery);
      }, [debouncedQuery]);
      
      return <input value={query} onChange={e => setQuery(e.target.value)} />;
    }

    Expected result

    Typing 'abc' quickly triggers only one search after 500ms of inactivity.

  3. 3

    Build useFetch

    Create a hook that fetches data from a URL and returns { data, loading, error }. Handle the cleanup case to avoid setting state after unmount.

    Code
    function useFetch(url) {
      const [data, setData] = useState(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);
      
      useEffect(() => {
        let cancelled = false;
        setLoading(true);
        fetch(url)
          .then(res => res.json())
          .then(data => { if (!cancelled) { setData(data); setLoading(false); } })
          .catch(err => { if (!cancelled) { setError(err); setLoading(false); } });
        return () => { cancelled = true; };
      }, [url]);
      
      return { data, loading, error };
    }

    Expected result

    Returns loading=true initially, then data or error when the fetch completes.

  4. 4

    Compose hooks together

    Use useDebounce with useFetch to create a debounced search that fetches results only after the user stops typing. This demonstrates hook composition.

    Code
    function SearchResults() {
      const [query, setQuery] = useState('');
      const debounced = useDebounce(query, 500);
      const { data, loading } = useFetch(
        debounced ? `/api/search?q=${debounced}` : null
      );
      
      return (
        <div>
          <input value={query} onChange={e => setQuery(e.target.value)} />
          {loading && <p>Loading...</p>}
          {data && <ul>{data.map(item => <li key={item.id}>{item.name}</li>)}</ul>}
        </div>
      );
    }

    Expected result

    Search fetches fire only after 500ms of inactivity, not on every keystroke.

  5. 5

    Test the hooks

    Write a simple test component that uses all three hooks and verify: localStorage persists, debounce delays, and fetch loads data. Use React DevTools to inspect state.

Try it yourself

What you learned

You built reusable custom hooks — the React way to share stateful logic across components without render props or HOCs. Hooks compose naturally.

Related Resources

Related Lessons

  • React Hooks

    Custom hooks build on useState and useEffect.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic