React hooks
Hooks give a function component memory, side effects and a link to the rest of the app. The useEffect hook is only for syncing with the outside world, not for computing data. If you understand the rules of hooks, the dependency array, cleanup and the stale closure problem, and you know the React 19 Actions for forms, you can answer most interview questions.
Author: bezzad
Contents
The problem: a product page that shows the wrong product
The product page of our shop has three bug reports:
- A user on slow internet clicks quickly between a few products. In the end the page title says “Shoes”, but the details show “Hat”.
- The sale timer gets stuck at 59 seconds and does not go down.
- The filtered product list renders twice on every key press, and sometimes shows old data for a moment.
All three bugs come from using hooks the wrong way. In this lesson we see how hooks work, and where not to use them.
The rules of hooks, and why
A hook is a function whose name starts with use, like useState and useEffect. There are two rules:
- Call hooks only at the top level of a component or a custom hook. Not inside an if, not inside a loop, not after an early return, not inside another function.
- Call hooks only from React components or custom hooks, not from a normal function.
Why? React does not know the names of your states. It only knows the call order:
- On every render, React has a list of slots for this component.
- The first hook reads slot 1, the second reads slot 2, and so on.
- If a hook is inside an if and is not called this time, every hook after it moves one slot and reads the data of another hook.
The eslint-plugin-react-hooks plugin checks these rules while you write code. Always keep it on.
Effects are for syncing with the outside world
The useEffect hook runs code after the commit. Its job is to sync the component with an outside system: the network, a timer, browser APIs like the page title or an event listener, or a widget that is not React.
Many effects are not needed. For example, this code keeps the filtered list in a separate state:
// Bad: an extra state and an extra render on every change
const [filtered, setFiltered] = useState<Product[]>([]);
useEffect(() => {
setFiltered(products.filter(p => p.name.includes(query)));
}, [products, query]);
- First, the component renders and commits with the old list.
- Then the effect runs and calls set.
- A second render happens with the right list. So the work doubled, and one commit had old data that the user may see for a moment.
// Good: compute it during render
const filtered = products.filter(p => p.name.includes(query));
Two simple rules:
- If something can be computed from props or state, compute it during render. If it is slow, use useMemo.
- If some work happens because of a user event, like sending the order after a click on “Pay”, it belongs in the event handler, not in an effect.
The dependency array and cleanup
The second argument of useEffect says when the effect runs again:
- No array: after every render.
- An empty array: only after the first time on screen (mount).
- An array with values: every time one of those values changes. The comparison uses Object.is.
Every value from props or state that the effect uses must be in the array. The eslint plugin checks this too.
An effect can return a cleanup function. React calls it before the effect runs again, and when the component is removed (unmount):
import { useEffect } from 'react';
function CartDrawer({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
useEffect(() => {
if (!isOpen) return;
function handleKey(e: KeyboardEvent) {
if (e.key === 'Escape') onClose();
}
window.addEventListener('keydown', handleKey);
return () => window.removeEventListener('keydown', handleKey); // cleanup
}, [isOpen, onClose]);
return isOpen ? <aside className="cart-drawer">Your cart</aside> : null;
}
The stale closure problem
Each render makes its own functions with the values of that render. If an old function stays alive, it sees old values. Our sale timer has exactly this problem:
import { useEffect, useState } from 'react';
export function SaleTimer() {
const [secondsLeft, setSecondsLeft] = useState(60);
useEffect(() => {
const id = setInterval(() => {
setSecondsLeft(secondsLeft - 1); // always 60 - 1
}, 1000);
return () => clearInterval(id);
}, []);
return <p>Sale ends in {secondsLeft} s</p>;
}
- The effect runs only once, because the dependency array is empty.
- The function inside setInterval was made in the first render, and in that render secondsLeft is 60.
- Every second, the same function sends 59. The number stays at 59.
The fix here is an updater function, because we no longer need to read the current value from the closure:
setSecondsLeft(s => s - 1); // React passes the latest value
Both timers start at 60, and the function inside setInterval runs once every second. Both have an empty dependency array.
setSecondsLeft(secondsLeft - 1)60The base value for this update: 60setSecondsLeft(s => s - 1)60The base value for this update: 60- If the effect really needs the fresh value, add that value to the dependency array. The effect is made again with the new value.
- If you only want to read the latest value and you do not want the effect to run again, the useEffectEvent hook (stable since React 19.2) makes a function that always sees fresh values.
Fetching data in an effect
Fetching data is syncing with a server, so if you have no library, it belongs in an effect. But you must ignore old responses:
import { useEffect, useState } from 'react';
type Product = { id: string; name: string; price: number };
export function ProductDetails({ productId }: { productId: string }) {
const [product, setProduct] = useState<Product | null>(null);
useEffect(() => {
let ignore = false;
async function load() {
const res = await fetch(`/api/products/${productId}`);
const data: Product = await res.json();
if (!ignore) setProduct(data); // skip answers for an old productId
}
load();
return () => { ignore = true; };
}, [productId]);
if (!product) return <p>Loading...</p>;
return <h1>{product.name}</h1>;
}
- Without the ignore flag, if the answer for the old product arrives later, it is written over the new product. This is the first bug of this lesson (a race condition).
- The AbortController class does the same, and also cancels the network request itself.
- In a real project, a data library like TanStack Query, or a framework loader (like React Router or Next.js), is usually better. They handle caching, duplicate requests, retries, and this same response-order problem for you.
The useRef hook
The useRef hook gives you a box whose value stays between renders, but changing it does not start a new render. It has two main uses: holding a DOM node, and holding values like a timer id.
import { useRef, type Ref } from 'react';
// React 19: ref is a normal prop, no forwardRef needed
function SearchInput({ ref }: { ref: Ref<HTMLInputElement> }) {
return <input ref={ref} type="search" placeholder="Search products" />;
}
export function Header() {
const inputRef = useRef<HTMLInputElement>(null);
return (
<header>
<SearchInput ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>Search</button>
</header>
);
}
Do not read or change the current property during render. Do it in an event handler or an effect. If a value must be visible on the page, it belongs in state, not in a ref.
The useMemo and useCallback hooks, and the memo function
By default, when a component renders, all of its children render too. This is usually fast and is not a problem.
- The memo function wraps a component so that its render is skipped when all props are equal by Object.is.
- A new object or function made on every render is not equal to the old one. So it makes memo useless.
- The useMemo hook keeps the result of a calculation, and the useCallback hook keeps a function itself, between renders, as long as the dependencies do not change.
import { memo, useCallback, useMemo, useState } from 'react';
type Product = { id: string; name: string; price: number };
type ListProps = { products: Product[]; onAdd: (id: string) => void };
const ProductList = memo(function ProductList({ products, onAdd }: ListProps) {
return (
<ul>
{products.map(p => (
<li key={p.id}>{p.name} <button onClick={() => onAdd(p.id)}>Add</button></li>
))}
</ul>
);
});
export function Shop({ products }: { products: Product[] }) {
const [query, setQuery] = useState('');
const [cartIds, setCartIds] = useState<string[]>([]);
const visible = useMemo(
() => products.filter(p => p.name.toLowerCase().includes(query.toLowerCase())),
[products, query],
);
const handleAdd = useCallback((id: string) => setCartIds(ids => [...ids, id]), []);
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<p>{cartIds.length} items in cart</p>
<ProductList products={visible} onAdd={handleAdd} />
</>
);
}
Use these tools only when you have measured and seen a slowdown, for example with the React DevTools Profiler. Each one has a cost and makes the code busier. The React Compiler is an optional build tool that can do this memoization for you.
The useContext hook and re-renders
Context sends data deep down without passing props through many layers. In React 19 you render the context itself as the provider:
import { createContext, useContext, useMemo, useState, type ReactNode } from 'react';
type CartItem = { productId: string; quantity: number };
type CartContextValue = { items: CartItem[]; add: (productId: string) => void };
const CartContext = createContext<CartContextValue | null>(null);
export function CartProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<CartItem[]>([]);
const value = useMemo(() => ({
items,
add: (productId: string) => setItems(prev => [...prev, { productId, quantity: 1 }]),
}), [items]);
return <CartContext value={value}>{children}</CartContext>;
}
export function useCart() {
const cart = useContext(CartContext);
if (!cart) throw new Error('useCart must be used inside CartProvider');
return cart;
}
- When the value changes (by Object.is), every component that reads this context renders again, even inside memo.
- If the value is a new object on every render, all readers render every time the provider renders. That is why useMemo is needed.
- Do not build one big context for everything. Put data that changes at different speeds, like the cart and the theme, in separate contexts.
Custom hooks
A custom hook is a function whose name starts with use and that calls other hooks. It shares logic, not state. Each component that calls it has its own separate state.
import { useEffect, useState } from 'react';
export function useDebouncedValue<T>(value: T, delayMs: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id); // a new key press cancels the old timer
}, [value, delayMs]);
return debounced;
}
The search box can now change state on every key press, but send a request only when the user has not typed for 300 milliseconds.
Actions in React 19
An Action is a function (usually async) that runs inside a transition. React manages the pending state, errors and optimistic updates for you. Here is the coupon form on the checkout page:
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
type CouponState = { message: string | null };
async function applyCoupon(_prev: CouponState, formData: FormData): Promise<CouponState> {
const res = await fetch('/api/coupons', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: formData.get('code') }),
});
return { message: res.ok ? 'Coupon applied' : 'This code is not valid' };
}
function SubmitButton() {
const { pending } = useFormStatus(); // status of the parent form
return <button type="submit" disabled={pending}>{pending ? 'Checking...' : 'Apply'}</button>;
}
export function CouponForm() {
const [state, formAction] = useActionState(applyCoupon, { message: null });
return (
<form action={formAction}>
<input name="code" placeholder="Coupon code" />
<SubmitButton />
{state.message && <p role="status">{state.message}</p>}
</form>
);
}
- The action attribute on the form tag takes a function. When the form is sent, React calls it with the FormData.
- The useActionState hook keeps the result of the last run in state, and returns three things: the state, a function for the form action, and isPending.
- The useFormStatus hook gives the status of the parent form. It must be called in a component inside the form, not in the same component that renders the form.
- The useOptimistic hook shows a temporary value until the Action ends. For example, the “Save to wishlist” button fills at once, and when the Action ends, the real value takes its place.
import { startTransition, useOptimistic } from 'react';
type Props = { saved: boolean; onToggle: (next: boolean) => Promise<void> };
export function WishlistButton({ saved, onToggle }: Props) {
const [optimisticSaved, setOptimisticSaved] = useOptimistic(saved);
function handleClick() {
startTransition(async () => {
setOptimisticSaved(!optimisticSaved); // show the new state now
await onToggle(!optimisticSaved); // when this ends, React shows the real saved prop
});
}
return <button onClick={handleClick}>{optimisticSaved ? 'Saved' : 'Save'}</button>;
}
The useTransition hook and the use API
The useTransition hook marks an update as not urgent. While rendering it, React can stop and answer more urgent work, like the user typing:
import { useState, useTransition } from 'react';
type Category = 'all' | 'shoes' | 'bags';
export function CategoryTabs() {
const [category, setCategory] = useState<Category>('all');
const [isPending, startTransition] = useTransition();
function select(next: Category) {
startTransition(() => setCategory(next)); // the big list can wait
}
return (
<div style={{ opacity: isPending ? 0.6 : 1 }}>
<button onClick={() => select('shoes')}>Shoes</button>
<button onClick={() => select('bags')}>Bags</button>
<p>Showing: {category}</p>
</div>
);
}
The use function reads a promise or a context. If the promise is not finished yet, the component waits (suspends), and the closest Suspense shows a loading state. Unlike hooks, it can be called inside an if. But do not create the promise during render. It must come from a cache or a framework, or a new promise is made on every render.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| A hook inside an if or after an early return | Hooks read each other’s data, or React throws an error. | All hooks at the top of the component. |
| An effect to compute derived data | An extra render and a commit with old data. | Compute it during render. |
| A timer with an empty array that reads state | The value is stuck at the first render. | An updater function or the right dependencies. |
| Fetching data without cleanup | An old response lands on new data. | An ignore flag or AbortController, or a data library. |
| Turning off StrictMode because the effect runs twice | The cleanup bug stays hidden. | Write a correct cleanup. |
| A new object or function as a prop of a memo component | The memo function does nothing. | The useMemo or useCallback hook, only if needed. |
| One big context with a new value on every render | All readers render on every change. | The useMemo hook and separate contexts. |
| The useFormStatus hook in the same component as the form | The pending value is always false. | A child component inside the form. |
Summary in 7 lines
- Always call hooks at the top of the component, in a fixed order. React finds them by their order.
- The useEffect hook is only for syncing with the outside world. Compute derived data during render, and do event work in event handlers.
- Put every value you use in the dependency array, and write a cleanup for every subscription or timer.
- Each render has its own closure. For a fresh value, use an updater function, the right dependencies or useEffectEvent.
- When fetching data, ignore old responses, or better, use a data library or a framework loader.
- Use memo, useMemo and useCallback only after measuring. Keep the context value stable and split contexts.
- For forms, use the React 19 Actions: useActionState, useFormStatus and useOptimistic.