You might not need an effect
Overview
useEffect is the most overused hook in React. Many effects in real codebases don’t synchronise with anything external — they shuffle data between state variables, causing extra renders, flickers and bugs. Removing them makes code shorter, faster and easier to follow.
The question to ask of every effect: “Which external system am I synchronising with?” If there isn’t one, you probably don’t need the effect.
1. Transforming data for rendering
// ✗ An effect to keep fullName in sync
const [firstName, setFirstName] = useState('Asha');
const [lastName, setLastName] = useState('Rao');
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);This renders twice on every change: once with a stale fullName, then again after the effect sets it. Just calculate it:
// ✓ Derived during render
const fullName = `${firstName} ${lastName}`;The same applies to filtered lists, sorted arrays, totals and validation flags. If the calculation is genuinely expensive, cache it with useMemo — still no effect:
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);(With React Compiler, even useMemo is usually unnecessary — see React Compiler.)
2. Handling user events
// ✗ Running purchase logic in an effect
const [submitted, setSubmitted] = useState(false);
useEffect(() => {
if (submitted) {
post('/api/register', { email });
showToast('Thanks for registering!');
}
}, [submitted]);The registration happens because the user clicked Submit, not because a component displayed. Put it in the handler:
// ✓ In the event handler
function handleSubmit(e) {
e.preventDefault();
post('/api/register', { email });
showToast('Thanks for registering!');
}Effect-based event logic also misfires: if the component remounts while submitted is true, the request is sent again. Ask yourself why the code should run. “Because the user did X” → event handler. “Because the component is visible” → effect.
3. Resetting state when a prop changes
// ✗ Clearing state after rendering with stale data
function ProfilePage({ userId }) {
const [comment, setComment] = useState('');
useEffect(() => {
setComment('');
}, [userId]);
}For one render, the new user’s profile shows the old user’s comment. Use a key to tell React it’s a different profile (see Preserving and resetting state):
// ✓ Different key → fresh state
<Profile userId={userId} key={userId} />Adjusting part of the state
If only some state should change when a prop changes, first check whether you can avoid storing it at all — usually by storing an id and deriving the object:
// Instead of storing `selection` and clearing it when `items` changes…
const [selectedId, setSelectedId] = useState(null);
const selection = items.find((item) => item.id === selectedId) ?? null; // null if it disappeared4. Sharing logic between handlers
// ✗ Showing a notification whenever the product is in the cart
useEffect(() => {
if (product.isInCart) {
showNotification(`Added ${product.name} to the cart!`);
}
}, [product]);This fires again whenever the page reloads with the item already in the cart. Extract a function and call it from the handlers that need it:
// ✓ Shared function, called from events
function buyProduct() {
addToCart(product);
showNotification(`Added ${product.name} to the cart!`);
}
function handleBuyClick() { buyProduct(); }
function handleCheckoutClick() { buyProduct(); navigate('/checkout'); }5. Chains of effects
// ✗ Effects triggering effects
useEffect(() => { if (card?.gold) setGoldCount((c) => c + 1); }, [card]);
useEffect(() => { if (goldCount > 3) { setRound((r) => r + 1); setGoldCount(0); } }, [goldCount]);
useEffect(() => { if (round > 5) setIsGameOver(true); }, [round]);Each step causes another render, and the logic is scattered. Compute the whole next state in the event handler (or a reducer):
// ✓ One place, one render
function handlePlaceCard(nextCard) {
if (isGameOver) throw new Error('Game already ended.');
setCard(nextCard);
if (nextCard.gold) {
if (goldCount < 3) {
setGoldCount(goldCount + 1);
} else {
setGoldCount(0);
setRound(round + 1);
if (round === 5) alert('Good game!');
}
}
}6. Notifying parents of changes
// ✗ Telling the parent after the fact
function Toggle({ onChange }) {
const [isOn, setIsOn] = useState(false);
useEffect(() => {
onChange(isOn);
}, [isOn, onChange]);
}Call the parent in the same handler that updates state — React batches both updates into one render:
// ✓
function Toggle({ onChange }) {
const [isOn, setIsOn] = useState(false);
function updateToggle(next) {
setIsOn(next);
onChange(next);
}
return <button onClick={() => updateToggle(!isOn)}>{isOn ? 'On' : 'Off'}</button>;
}Or lift the state up and make Toggle fully controlled by its parent.
7. Initialising the app
Code that should run once per app load (not once per mount — remember StrictMode mounts twice) can live outside components:
if (typeof window !== 'undefined') {
checkAuthToken();
loadDataFromLocalStorage();
}
function App() { … }What effects are for
Keep effects for real synchronisation with things React doesn’t control:
- browser APIs: event listeners,
IntersectionObserver,matchMedia, document title, - timers and intervals that run while a component is visible,
- network connections and subscriptions: WebSockets, server-sent events,
- non-React widgets: maps, charts, video players, editors,
- data fetching — though a library or framework usually does it better (next chapter).
Litmus test: delete the effect mentally. If the UI would just need to compute something or respond to a click, you didn’t need it.
Remove the effects
This Checkout component uses three effects. Rewrite it without any of them: the total should be derived, the analytics call should happen in the event handler that caused it, and the coupon field should reset when userId changes (use a key in the parent — write the parent too).
import { useEffect, useState } from 'react';
export function Checkout({ items, userId, onPurchase, track }) {
const [total, setTotal] = useState(0);
const [coupon, setCoupon] = useState('');
const [purchased, setPurchased] = useState(false);
useEffect(() => {
setTotal(items.reduce((s, i) => s + i.price, 0));
}, [items]);
useEffect(() => {
if (purchased) {
track('purchase', { total });
onPurchase();
}
}, [purchased]);
useEffect(() => {
setCoupon('');
}, [userId]);
return (
<div>
<p>Total: ${total}</p>
<input aria-label="Coupon" value={coupon} onChange={(e) => setCoupon(e.target.value)} />
<button onClick={() => setPurchased(true)}>Buy</button>
</div>
);
}import { useState } from 'react';
export function Checkout({ items, onPurchase, track }) {
const [coupon, setCoupon] = useState('');
const total = items.reduce((s, i) => s + i.price, 0); // derived
function handleBuy() {
// the purchase is caused by this click, so its side effects live here
track('purchase', { total, coupon });
onPurchase();
}
return (
<div>
<p>Total: ${total}</p>
<input aria-label="Coupon" value={coupon} onChange={(e) => setCoupon(e.target.value)} />
<button onClick={handleBuy}>Buy</button>
</div>
);
}
export function CheckoutPage({ items, userId, onPurchase, track }) {
// a new userId means a new Checkout, so all its state resets
return <Checkout key={userId} items={items} onPurchase={onPurchase} track={track} />;
}Summary
- If a value can be calculated from props or state, calculate it during render — don’t sync it with an effect.
- Code that runs because of a user action belongs in the event handler, not in an effect watching state.
- Reset all state when a prop changes with a
key; adjust part of it during render if you must. - Avoid chains of effects that set state to trigger other effects; compute the next state in one place.
- Effects are for synchronising with external systems — ask ‘what external system is this?’