React Hooks Explained: useState, useEffect, and Beyond
Hooks let function components hold state and respond to lifecycle events without writing a class. Once the mental model clicks, they make components easier to read and test than the class-based alternative they replaced.
useState: Local Component State
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
Calling setCount schedules a re-render with the new value. If the new state depends on the previous one, pass a function instead of a value to avoid stale-state bugs:
setCount((prev) => prev + 1);
useEffect: Syncing With the Outside World
useEffect runs side effects — fetching data, subscribing to an event, manually touching the DOM — after a component renders:
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => res.json())
.then(setUser);
return () => controller.abort();
}, [userId]);
The dependency array ([userId]) controls when the effect re-runs. The returned function is a cleanup that runs before the next effect, or when the component unmounts — here it cancels an in-flight request if userId changes quickly.
Common useEffect Mistakes
- Missing dependencies. Omitting a value the effect reads from outer scope causes stale closures — the effect keeps using an old value.
- No dependency array at all. This runs the effect after every single render, often unintentionally.
- Using it for derived state. If a value can be computed directly from props or state, compute it during render instead of syncing it into state with an effect.
useMemo and useCallback
These memoize a computed value or a function reference between renders, which matters mainly when passing them to a memoized child component or using them inside another hook's dependency array:
const sortedItems = useMemo(() => items.slice().sort(compare), [items]);
const handleClick = useCallback(() => doSomething(id), [id]);
They're an optimization, not a default — reach for them when you notice unnecessary re-computation or re-renders, not preemptively on every value.
Custom Hooks: Extracting Reusable Logic
Any function starting with use that calls other hooks is a custom hook, and it's the standard way to share stateful logic between components:
function useDebouncedValue(value, delayMs) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(timer);
}, [value, delayMs]);
return debounced;
}
Summary
useState and useEffect cover the majority of day-to-day component needs. useMemo/useCallback are targeted performance tools, and custom hooks are how you avoid copy-pasting the same stateful logic across components. Understanding the dependency array is the single most important piece for avoiding subtle bugs with all of them.
