Custom Hooks
Extracting and reusing stateful logic with custom hooks
Skills taught: react.custom-hooks, react.hook-rules, react.useFetch, react.useLocalStorage
Building custom hooks
// Custom hook: useFetch — reusable data fetching with loading/error states
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false;
setLoading(true);
setData(null);
setError(null);
fetch(url)
.then(res => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); })
.then(json => { if (!ignore) { setData(json); setLoading(false); } })
.catch(err => { if (!ignore) { setError(err.message); setLoading(false); } });
return () => { ignore = true; };
}, [url]);
return { data, loading, error };
}
// Custom hook: useLocalStorage — persist state in localStorage
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
} catch { return initialValue; }
});
const set = (newValue) => {
setValue(newValue);
try { localStorage.setItem(key, JSON.stringify(newValue)); } catch {}
};
return [value, set];
}
// Custom hook: useToggle
function useToggle(initial = false) {
const [state, setState] = useState(initial);
const toggle = () => setState(s => !s);
return [state, toggle];
}
// Use all three in one component
function App() {
const { data: post, loading, error } = useFetch('https://jsonplaceholder.typicode.com/posts/1');
const [name, setName] = useLocalStorage('kernal-name', '');
const [isExpanded, toggleExpanded] = useToggle(false);
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px', maxWidth: '400px' }}>
<div style={{ marginBottom: '12px' }}>
<input value={name} onChange={e => setName(e.target.value)} placeholder="Saved name (localStorage)" style={{ padding: '6px', width: '100%', boxSizing: 'border-box' }} />
{name && <p>Hello, {name}! (persisted across page loads)</p>}
</div>
{loading && <p>Loading post...</p>}
{error && <p style={{ color: 'red' }}>Error: {error}</p>}
{post && (
<div style={{ border: '1px solid #e2e8f0', borderRadius: '8px', padding: '12px' }}>
<h3 style={{ margin: '0 0 8px' }}>{post.title}</h3>
<button onClick={toggleExpanded}>{isExpanded ? 'Collapse' : 'Expand'}</button>
{isExpanded && <p style={{ marginTop: '8px' }}>{post.body}</p>}
</div>
)}
</div>
);
}
Frequently Asked Questions
Why must custom hook names start with 'use'?
This is enforced by the react-hooks ESLint plugin. It's how React (and the linter) knows to apply the rules of hooks to your function: no conditional calls, always called in the same order. A function named 'fetchData' (without 'use') won't be checked — you could accidentally call it conditionally and violate hook rules silently.