Custom Hooks
Extracting reusable stateful logic into custom hooks and the rules of hooks.
What you'll learn
- What custom hooks are and why they are powerful
- How to extract stateful logic into a reusable hook
- The rules of hooks and naming conventions
- Composing hooks inside other hooks
Concept
What Are Custom Hooks?
A custom hook is a JavaScript function whose name starts with use and that may call other hooks inside it. Custom hooks let you extract component logic into reusable functions, just like regular functions extract reusable calculations. If you find yourself copying the same useState and useEffect patterns across multiple components, you can extract that logic into a custom hook and reuse it. This is one of the most powerful features of React.
Extracting Logic
For example, a useWindowSize hook could encapsulate the logic for tracking the window dimensions. A useLocalStorage hook could sync a state value to localStorage. A useFetch hook could handle loading, data, and error states for API calls. Each hook returns whatever the consuming component needs — state values, handlers, or an object with multiple properties. The hook manages its own state internally, and each component that calls the hook gets its own independent state.
The Rules of Hooks
Custom hooks must follow the Rules of Hooks: only call hooks at the top level (not inside loops, conditions, or nested functions), and only call hooks from React function components or other custom hooks. The use prefix is not just convention — React's linter plugin relies on it to enforce the rules. Never call a hook inside a regular function that is not a component or hook.
Composing Hooks
Custom hooks can call other custom hooks, creating composable layers of logic. A useUserData hook might call useFetch and useLocalStorage. This composition lets you build complex behavior from simple, testable pieces. Keep hooks focused on one concern, and name them descriptively. Test hooks in isolation with React Testing Library or by rendering a small test component.
Return Value Patterns
Custom hooks can return a single value, an array (like useState), or an object with named properties. Returning an array lets consumers rename the values: const [data, loading] = useFetch(url). Returning an object is better when there are many properties or when consumers only need some: const { data, error } = useFetch(url). Choose the pattern that makes the consuming code clearest.
Example
import { useState, useEffect } from "react";
// Custom hook: tracks a value synced to localStorage.
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];
}
// Custom hook: tracks window size.
function useWindowSize() {
const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight });
useEffect(() => {
const handler = () => setSize({ width: window.innerWidth, height: window.innerHeight });
window.addEventListener("resize", handler);
return () => window.removeEventListener("resize", handler);
}, []);
return size;
}
// Using both custom hooks in a component.
function App() {
const [name, setName] = useLocalStorage("username", "Guest");
const { width, height } = useWindowSize();
return (
<div>
<p>Window: {width} x {height}</p>
<input value={name} onChange={e => setName(e.target.value)} />
</div>
);
}
useLocalStorage and useWindowSize are custom hooks that encapsulate reusable logic. Each component calling them gets independent state. Hooks compose naturally.
Try it
- JSON Formatter
Custom hooks often return objects — format to inspect their shape.
- Code Diff
Compare hook implementations when refactoring shared logic.
Common mistakes
The mistake
Not starting the hook name with 'use'
The fix
React's linter and rules of hooks rely on the 'use' prefix. A function that calls hooks must be named useSomething. Without it, the linter cannot detect hook violations.
The mistake
Breaking the rules of hooks inside custom hooks
The fix
Custom hooks must call hooks at the top level only — never inside conditions, loops, or nested functions. The same rules apply inside custom hooks as inside components.
Practice Custom Hooks
5 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.