Hooks are the way modern React components hold state, run side effects and reuse logic. Introduced in React 16.8, they replaced most class components, and they are the part of React that trips up newcomers most often. This guide explains the hooks you will use every day, with practical examples and the mistakes I see most often in code reviews.
All examples assume you already know basic JavaScript. If you need a refresher, start with the JavaScript tutorial for beginners.
What is a hook?
A hook is a function that lets a function component “hook into” React features. Hook names start with use, and two rules apply: call hooks only at the top level of a component (never inside loops, conditions or nested functions), and call them only from React components or other hooks. React relies on the order of hook calls staying the same between renders, which is why those rules exist.
useState: remembering values
useState returns the current value and a function to update it. Calling the setter schedules a re-render with the new value.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount((c) => c + 1)}>
Clicked {count} times
</button>
);
}
Notice setCount((c) => c + 1). When the next value depends on the previous one, pass a function. It always receives the latest value, even when several updates are batched together.
Never mutate state
React compares references to decide whether to re-render. Create new arrays and objects instead of changing existing ones.
const [todos, setTodos] = useState([]);
// Add
setTodos((prev) => [...prev, { id: Date.now(), text: "Learn hooks", done: false }]);
// Toggle
setTodos((prev) => prev.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
// Remove
setTodos((prev) => prev.filter((t) => t.id !== id));
useEffect: side effects
A side effect is anything that reaches outside rendering: fetching data, subscribing to events, updating the document title. useEffect runs after the component renders, and its dependency array controls when it runs again.
import { useEffect, useState } from "react";
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error("Request failed");
return res.json();
})
.then(setUser)
.catch((err) => {
if (err.name !== "AbortError") setError(err.message);
});
return () => controller.abort(); // cleanup when userId changes or the component unmounts
}, [userId]);
if (error) return <p>Something went wrong.</p>;
if (!user) return <p>Loading…</p>;
return <h2>{user.name}</h2>;
}
Three things to remember. The dependency array should list every reactive value the effect uses. An empty array [] means “run once after the first render”. The returned function is cleanup, which runs before the next effect and on unmount. That cleanup is what prevents race conditions and memory leaks.
You might not need an effect
If you can calculate a value from props or state during rendering, do that instead of storing it in state and syncing it with an effect. The official docs have a great page on this, You Might Not Need an Effect.
useRef: values that do not trigger renders
useRef gives you a mutable box whose .current property survives re-renders without causing one. The most common use is reaching a DOM element.
import { useRef } from "react";
function SearchBox() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} placeholder="Search…" />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</>
);
}
useMemo and useCallback: performance tools, not defaults
useMemo caches the result of a calculation, and useCallback caches a function so its identity stays stable between renders.
import { useMemo } from "react";
function ProductList({ products, query }) {
const visible = useMemo(
() => products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase())),
[products, query]
);
return <ul>{visible.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
Use these when you have measured a real slowdown, such as filtering thousands of rows or passing a callback to a memoised child component. Wrapping everything in them adds noise and rarely helps.
useContext: sharing data without prop drilling
Context lets a parent provide a value that any descendant can read, which is handy for the current theme, the logged-in user or a language setting.
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext("light");
function App() {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={theme}>
<Toolbar onToggle={() => setTheme((t) => (t === "light" ? "dark" : "light"))} />
</ThemeContext.Provider>
);
}
function Toolbar({ onToggle }) {
const theme = useContext(ThemeContext);
return <button onClick={onToggle}>Current theme: {theme}</button>;
}
Custom hooks: reusing logic
When two components need the same stateful logic, extract it into your own hook. A custom hook is just a function that starts with use and calls other hooks. Here is one that keeps state in localStorage:
import { useEffect, useState } from "react";
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const saved = localStorage.getItem(key);
return saved !== null ? JSON.parse(saved) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
/* storage may be unavailable */
}
}, [key, value]);
return [value, setValue];
}
// Usage
const [theme, setTheme] = useLocalStorage("theme", "light");
Common mistakes to avoid
- Mutating state directly (
todos.push(x)) instead of creating a new array. - Leaving values out of the dependency array, which causes stale data. The
react-hooks/exhaustive-depsESLint rule catches this. - Creating an infinite loop by setting state inside an effect that depends on that same state.
- Fetching data in an effect without cleanup, so a slow old response overwrites a newer one.
- Calling hooks conditionally, for example after an early
return. - Reaching for
useMemoanduseCallbackeverywhere before measuring.
Where to go next
Build a small project that uses all of the above: a notes app with useState for the list, useEffect for loading and saving, a custom useLocalStorage hook and context for the theme. The official React Hooks reference documents every built-in hook with examples. If you want your components to look right on every screen, pair this with responsive design using HTML and CSS.