Custom Hooks Collection
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
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.
Codeimport { 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
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.
Codefunction 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
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.
Codefunction 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
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.
Codefunction 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
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.
Hint
For the cancelled flag in useFetch, try unmounting the component during a fetch — no warning should appear.
Try it yourself
import { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
// TODO: useState + useEffect to sync with localStorage
}function useLocalStorage(k, v) { const [s, set] = useState(() => JSON.parse(localStorage.getItem(k) || 'null') ?? v); useEffect(() => localStorage.setItem(k, JSON.stringify(s)), [k, s]); return [s, set]; }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.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.