Skip to main content

You might not need an Effect

Effects are escape hatches. They are not the default place for application logic.

A strong React engineer tries to keep logic in the simplest model that fits:

Where should this logic live?
Can it be calculated from current props/state during render?Calculate it during render.
Did a specific user interaction cause it?Run it in the event handler.
Is a different entity supposed to get a fresh state lifetime?Express the identity with structure or a key.
Do multiple components need one changing value?Choose one owner and lift/share the state.
Must React stay synchronized with something outside React?Use an Effect.

This chapter is about recognizing when an Effect is solving the wrong problem.

Derived data belongs in renderโ€‹

Bad:

const [firstName, setFirstName] = useState('Aisha');
const [lastName, setLastName] = useState('Khan');
const [fullName, setFullName] = useState('');

useEffect(() => {
setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);

Better:

const fullName = `${firstName} ${lastName}`;

Why?

Derived data should flow directly from its inputs
firstName + lastName
These are the real changing inputs.
fullName
No extra state or synchronization process is required.

The Effect version creates:

  • extra state;
  • an extra render;
  • synchronization code;
  • another place for bugs.

Filtering and sorting usually belong in renderโ€‹

Bad:

const [visibleProducts, setVisibleProducts] = useState([]);

useEffect(() => {
setVisibleProducts(
products.filter(product => product.name.includes(query)),
);
}, [products, query]);

Better:

const visibleProducts = products.filter(product =>
product.name.includes(query),
);

If the computation later becomes measurably expensive, performance techniques can be considered. Do not introduce an Effect merely because a calculation is non-trivial.

User actions belong in event handlersโ€‹

Bad:

const [submitted, setSubmitted] = useState(false);

useEffect(() => {
if (submitted) {
sendOrder(cart);
}
}, [submitted, cart]);

Better:

function handleSubmit() {
sendOrder(cart);
}

The order is sent because the user submitted the form, not because the component happened to render with submitted === true.

Avoid Effect chains for internal state transitionsโ€‹

Bad:

useEffect(() => {
if (card !== null) {
setGoldCardCount(c => c + 1);
}
}, [card]);

useEffect(() => {
if (goldCardCount > 3) {
setRound(r => r + 1);
setGoldCardCount(0);
}
}, [goldCardCount]);

This turns a simple event into a chain of renders and Effects.

Prefer calculating the complete transition in the event that caused it:

function handlePlaceCard(nextCard) {
setCard(nextCard);

if (nextCard) {
setGoldCardCount(current => {
const next = current + 1;

if (next > 3) {
setRound(r => r + 1);
return 0;
}

return next;
});
}
}

For complex transitions, a reducer may model the state machine more clearly.

Resetting state when a key changesโ€‹

Suppose a profile editor should reset when switching users.

A common Effect solution is:

function ProfilePage({userId}) {
const [comment, setComment] = useState('');

useEffect(() => {
setComment('');
}, [userId]);
}

But this is fundamentally an identity problem.

A clearer approach can be:

<ProfileEditor key={userId} userId={userId} />

Now React treats each user editor as distinct stateful identity.

Use identity when the state conceptually belongs to a different entity.

Adjusting state during render is usually a design smellโ€‹

Sometimes code tries to keep state synchronized with props:

const [selection, setSelection] = useState(null);

useEffect(() => {
setSelection(null);
}, [items]);

First ask whether you can store a stable identifier instead:

const [selectedId, setSelectedId] = useState(null);

const selection = items.find(item => item.id === selectedId) ?? null;

Now the current selection is derived from current data.

Informing a parent about state changesโ€‹

Bad:

function Toggle({onChange}) {
const [enabled, setEnabled] = useState(false);

useEffect(() => {
onChange(enabled);
}, [enabled, onChange]);
}

This causes the notification after rendering.

If the change comes from user interaction, notify both places in the same event:

function Toggle({onChange}) {
const [enabled, setEnabled] = useState(false);

function handleClick() {
const next = !enabled;
setEnabled(next);
onChange(next);
}
}

Or make the component controlled if the parent should own the source of truth.

Parent and child state duplicationโ€‹

If both parent and child need the same changing value, do not synchronize copies with Effects.

Duplicated state creates a synchronization problem
Parent copy
Parent believes it owns the current value.
Child copy
Child also stores the same fact, so the two copies can drift apart.

Prefer one source of truth:

Controlled flow keeps one owner
Parent owns state
One authoritative value.
Child renders the value
The child receives data rather than mirroring it.
Parent updates state
The owner decides the next value.

This is the controlled-component model.

Initializing application stateโ€‹

Sometimes developers use an empty-array Effect to initialize state:

useEffect(() => {
setTheme(loadTheme());
}, []);

If the value can be determined during state initialization, prefer a lazy initializer:

const [theme, setTheme] = useState(() => loadTheme());

This avoids a render with temporary state followed by an Effect-driven correction.

Expensive calculations are not Effectsโ€‹

Wrong mental model:

"This computation is expensive, so I should run it in an Effect."

Effects are about synchronization, not computation cost.

Start with:

const result = expensiveCalculation(data);

Then measure. If memoization is justified later:

const result = useMemo(() => expensiveCalculation(data), [data]);

Even then, the computation remains part of rendering logic.

Network requests caused by eventsโ€‹

Submitting a purchase:

function handleBuy() {
fetch('/api/order', {
method: 'POST',
body: JSON.stringify(cart),
});
}

This belongs in the event because the user caused it.

Fetching data because a route/component needs to stay synchronized with a remote resource may use an Effect in a simple client-only app, but larger applications often benefit from framework loaders or server-state libraries.

Analytics: event or Effect?โ€‹

Question:

Why is the analytics event happening?

If it means "user clicked checkout":

function handleCheckout() {
analytics.track('checkout_clicked');
}

If it means "this screen became active/visible": an Effect may be appropriate because the analytics is tied to rendered presence.

The important distinction is cause.

Common anti-pattern: Effect as command busโ€‹

Bad:

const [action, setAction] = useState(null);

useEffect(() => {
if (action === 'SAVE') save();
if (action === 'DELETE') remove();
}, [action]);

This converts direct imperative events into indirect state-driven commands.

Prefer calling the command from the event that caused it.

Decision tableโ€‹

ProblemUsually use
Calculate a value for JSXrender logic
Respond to click/submit/inputevent handler
Share state between siblingslift state
Reset state for a different entitykey / identity
Model complex state transitionsreducer
Store mutable non-render dataref
Synchronize browser/network/widget/subscriptionEffect

Debugging unnecessary Effectsโ€‹

When reviewing an Effect, ask:

  1. What external system is this synchronizing with?
  2. If there is none, can the value be derived during render?
  3. Did a specific user interaction cause this work?
  4. Is duplicated state being synchronized?
  5. Is this really a component identity problem?
  6. Would lifting state remove the need for synchronization?
  7. Would a reducer better model a state transition?

Production exampleโ€‹

Imagine an ecommerce filter page.

Avoid:

Anti-pattern: derived values stored as synchronized state
query state
filteredProducts state
resultCount state
Three pieces of state now need to stay synchronized.

Prefer:

Preferred: one source of truth, derived during render
products + query
These are the real inputs.
filteredProducts
Derived from current inputs.
resultCount
Calculated from the filtered collection.

One source of truth produces multiple derived values.

Exerciseโ€‹

Refactor this component without Effects:

function Checkout({items, onTotalChange}) {
const [total, setTotal] = useState(0);

useEffect(() => {
setTotal(items.reduce((sum, item) => sum + item.price, 0));
}, [items]);

useEffect(() => {
onTotalChange(total);
}, [total, onTotalChange]);

return <strong>{total}</strong>;
}

Questions:

  • Which value is derived?
  • Who should own the total?
  • Does the parent really need a callback, or can it calculate the same value?

Interview questionsโ€‹

Junior: Give an example of logic that should be calculated during render instead of inside an Effect.

Mid-level: Why can Effect-driven derived state cause extra renders and synchronization bugs?

Senior: How do state ownership and component identity eliminate classes of Effects from an application architecture?

Summaryโ€‹

Effects are valuable precisely because they are specialized.

Use normal React data flow before reaching for an Effect
Inside React's data flow
Render calculations ยท events ยท state ownership ยท identity ยท reducers.
Effect escape hatch
Use when React must synchronize with something outside that normal data flow.

Referencesโ€‹

Nextโ€‹

Continue with Effect Lifecycle and Dependencies.