Understanding React Hooks
A deep dive into React Hooks: useState, useEffect,
and how they simplify functional components. Hooks let you use state and
lifecycle behavior without writing a class, which means less boilerplate,
fewer bugs around this, and logic that can be extracted and
reused.
useState
Allows you to add state to functional components. It returns a pair: the current value and a setter function that re-renders the component when called:
const [count, setCount] = useState(0);
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
- The initial value is only used on the first render.
- State updates are asynchronous and batched in React 18+.
- Use the functional form
setCount(c => c + 1)when the new value depends on the previous one.
useEffect
Runs side effects after render — fetching data, subscribing to events, or syncing with the DOM. The dependency array controls when it runs:
useEffect(() => {
fetch('/api/user').then(r => r.json()).then(setUser);
}, []); // empty array: run once, after mount
- Return a cleanup function to unsubscribe or cancel timers when the component unmounts.
- With
[]dependencies the effect runs once after mount; include variables to re-run when they change.
Other Common Hooks
useContext— read values from a React context without prop drilling.useReducer— state management with a reducer function, useful for complex state.useMemo— cache an expensive computation until its inputs change.useCallback— cache a function reference across renders.useRef— a mutable value that survives re-renders without triggering them (also used to access DOM nodes).
Rules of Hooks
- Only call hooks at the top level of a component — never inside loops, conditions or nested functions.
- Only call hooks from React functions (components or custom hooks).
These rules exist because React tracks hooks by their call order. Violating them produces the "Rendered more hooks than during the previous render" error.
Custom Hooks
Extract repeated logic into a custom hook — a plain function whose name
starts with use:
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
return width;
}
Conclusion
Hooks turned React state and side effects into plain functions, which made
components smaller, logic reusable, and testing simpler. Start with
useState and useEffect, follow the rules of hooks,
and extract a custom hook as soon as you notice repetition.