You might not need an effect

Topic 3 of 5 in Refs & effects8 min readIntermediateFree course

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.

A decision list. Can you calculate it from props or state? Compute it during render. Is it a response to a user action? Put it in the event handler. Is it fetching data? Use a data library or your framework. Do you need to reset state when a prop changes? Use a key. Syncing with something outside React? Yes — that’s what effects are for.

1. Transforming data for rendering

JSX
// ✗ 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:

JSX
// ✓ 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:

JSX
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);

(With React Compiler, even useMemo is usually unnecessary — see React Compiler.)

2. Handling user events

JSX
// ✗ 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:

JSX
// ✓ 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

JSX
// ✗ 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):

JSX
// ✓ 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:

JSX
// 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 disappeared

4. Sharing logic between handlers

JSX
// ✗ 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:

JSX
// ✓ 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

JSX
// ✗ 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):

JSX
// ✓ 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

JSX
// ✗ 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:

JSX
// ✓
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:

JSX
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.

Exercise

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).

JavaScript
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>
  );
}

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?’