Hooks are functions that give a React component abilities it would not otherwise have: remembering a value between renders, running code when something changes, reaching into shared data. There are only two you need to start, useState and useEffect, and a handful more you will meet within weeks. This article explains what each one does, shows working examples, and covers the two rules whose violation causes nearly every hooks bug.
Why hooks exist#
A React component is a function that returns what to show. React calls it every time it needs to update the screen. A plain function forgets everything between calls, so on its own a component cannot remember that a button was clicked. Hooks are how React lets the function keep things across calls: state that persists, effects that run when something changes.
useState#
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // current value, and a function to change it
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
useState(0) gives a pair: the value now, and a setter. Calling the setter with a new value tells React to re-render the component; on that render, useState returns the new value. That loop — event, setter, re-render — is most of React.
Two things people learn the hard way:
setCount(count + 1);
setCount(count + 1); // still only +1: both read the same old count
setCount(c => c + 1);
setCount(c => c + 1); // +2: each update sees the latest value
const [items, setItems] = useState([]);
items.push('new'); // mutates; React does not notice
setItems([...items, 'new']); // new array; React re-renders
Use the function form when the new value depends on the old, and always produce a new array or object rather than changing the existing one.
useEffect#
An effect is code that runs after React has updated the screen: fetching data, setting a title, subscribing to something. It is for reaching outside the component.
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
let cancelled = false;
fetch('/api/users/' + userId)
.then(r => r.json())
.then(data => { if (!cancelled) setUser(data); });
return () => { cancelled = true; }; // cleanup: runs before the next effect, and on unmount
}, [userId]); // re-run only when userId changes
if (!user) return <p>Loading…</p>;
return <h1>{user.name}</h1>;
}
The second argument, the dependency array, controls when the effect runs:
| Dependencies | Runs |
|---|---|
| Omitted | After every render. Rarely what you want. |
[] |
Once, after the first render. |
[userId] |
After the first render, and again whenever userId changes. |
The cleanup function matters for anything that could still be in flight when the component changes or disappears: a fetch that would set state on an unmounted component, a timer, a subscription. Return a function that undoes the effect.
The rules of hooks#
- Call hooks at the top level of the component, never inside a condition, a loop, or a nested function. React tracks hooks by the order they are called, so the order must be identical every render.
- Call hooks only from React function components or from other hooks. Not from plain functions, not from class components.
function Bad({ show }) {
if (show) {
const [x, setX] = useState(0); // breaks rule 1: order changes when show changes
}
}
function Good({ show }) {
const [x, setX] = useState(0); // always called
if (!show) return null;
}
The error Rendered more hooks than during the previous render is rule 1 being broken.
The other hooks you will use#
useRef holds a value that persists across renders without causing a re-render when it changes. Two uses: a handle to a DOM element, and a mutable box for things like timer ids.
const inputRef = useRef(null);
useEffect(() => { inputRef.current.focus(); }, []);
return <input ref={inputRef} />;
useContext reads a value provided somewhere above in the tree, so it does not have to be passed through every level as a prop. Theme, current user, language.
const ThemeContext = createContext('light');
// somewhere above: <ThemeContext.Provider value="dark">...</ThemeContext.Provider>
const theme = useContext(ThemeContext);
useMemo and useCallback cache a computed value or a function between renders so that expensive work is not redone and child components do not re-render needlessly. Reach for them when you have measured a problem, not by default; premature memoisation adds complexity and often no speed.
useReducer is useState for state with several related fields and transitions; if your setters are getting complicated, it is the next step.
Custom hooks#
Any function that calls hooks and starts with use is a custom hook. It is how you share stateful logic between components:
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
try { return JSON.parse(localStorage.getItem(key)) ?? initial; } catch { return initial; }
});
useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]);
return [value, setValue];
}
const [name, setName] = useLocalStorage('name', '');
The component using it does not know or care that storage is involved. Most real applications end up with a handful of these.
Questions people ask#
Do I still need class components?
No. Hooks cover everything classes did, and new React code is written with function components. You will meet classes in older codebases.
Why does my effect run twice in development?
React’s Strict Mode mounts components twice in development to surface effects that lack cleanup. It does not happen in production. If the double run causes a problem, the effect is missing its cleanup.
Should I fetch data in useEffect?
For learning, yes. In real applications, frameworks and libraries such as Next.js server components and TanStack Query handle fetching with caching and error handling; effects are the manual version.
What is the difference between useMemo and useCallback?
useMemo caches a value; useCallback caches a function. The second is the first applied to functions.
Where to go next#
- Next.js vs React — what the framework adds.
- Promises explained — the fetch inside the effect.
- Browser storage in JavaScript — behind the custom hook.