Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 132 ยท Hooks

You Might Not Need an Effect

Learn when not to use useEffect in React - derived state, resetting with keys, event handlers, effect chains, notifying parents and useSyncExternalStore - with before and after examples.

Effects are an escape hatch: a way to step outside React and synchronize with something that React does not own, like a timer, a socket or a third-party widget. They are not a general "run code when something changes" tool. Yet a very common beginner pattern is to reach for useEffect every time one value should follow another, and the result is code that renders twice, flickers, loops and is hard to follow.

This lesson is a catalogue of the situations where an effect looks natural but is wrong, with the better replacement for each. The guiding question is always: why does this code need to run? If the answer is "because the component was displayed" (it must stay in sync with an outside system), use an effect. If the answer is "because the user did something", use an event handler. If the answer is "because I can calculate it from what I already have", calculate it during rendering. Read Effects with useEffect first if you have not met effects yet.

Why unnecessary effects hurt

Every state update triggered from an effect costs an extra render. React renders your component, commits the result to the screen, runs the effect, which sets state, which renders and commits again. The user can see the first, wrong result for a frame. With chains of effects, the cost multiplies, and the data flow (who changes what, and when) disappears into a pile of "run this after that".

Rendering is cheap, and calculating during render is almost always the best place for logic: the output is correct on the very first paint, there is no stale intermediate state, and there is nothing to clean up.

1. Derived state: calculate, don't synchronize

If a value can be calculated from props or other state, it is not state. The tell-tale pattern is useState plus an effect that copies one thing into the other.

Derived state in an effect versus in render

Read the console from the top. WithEffect renders first with fullName = "" (the screen briefly shows an empty value) and then again with "Ada Lovelace". WithRender renders once with the right value. Edit a name and the same thing happens on every keystroke: two renders for the effect version, one for the other.

The fix is always the same: delete the state, delete the effect, write a plain const.

What if the calculation is expensive, like filtering ten thousand rows? Still no effect. Calculate in render, and if you have measured that it is slow, wrap the calculation in useMemo (useMemo and useCallback). The memo skips the work when its inputs are unchanged and still gives the right answer on the first render.

Don't copy props into state either (const [color, setColor] = useState(props.color)) unless you intend the prop to be only an initial value that is never synced again. Name such props initialColor to make that promise visible. Otherwise a parent that passes a new color will be silently ignored.

2. Resetting state when a prop changes

Suppose a draft box belongs to a user. When you switch users, the draft should clear. A common but poor approach is an effect on the user id that calls setDraft(''). It shows the old draft for one render (with the new user's name above it!) and then fixes itself.

React has a built-in way to say "this is a different thing, start from scratch": give the component a key. When the key changes, React discards the component instance and its state and creates a new one.

Reset with an effect versus with a key

Type hi into both boxes and press the button. For the effect version the console shows effect version render: user 2, draft "hi" (a wrong frame: user 2 with user 1's text) followed by a second render with the empty draft. The key version logs only key version render: user 2, draft "", because it is a brand-new component instance. Keys are explained properly in Rendering Lists and Keys and Reconciliation and Keys in Depth.

What if only part of the state should reset? Then adjust it while rendering, which is allowed for a component's own state (guarded by a condition so it cannot loop), or better, restructure the state so the part that changes is derived. Choosing a State Structure has the techniques.

3. Events belong in event handlers

An effect runs because the component rendered with certain values, not because the user did something. If code answers a click, a submit or a key press, put it in the handler, where you know exactly what happened.

Here is the classic bug. A product page shows a notification when the product is in the cart, so the developer put the notification in an effect. But "is in the cart" is a fact about state, not an event: it is also true when you navigate to a product you added last week.

Notification in an effect versus in a handler

The page starts on Coffee (not in cart) and nothing is logged. Press "Show Tea": the console prints NOTIFY: Added Tea to the cart! from the effect version, although nobody added anything. Only the handler version is right. Go back to Coffee and press the "Add" button of each version: both log NOTIFY: Added Coffee to the cart!, but only the handler version does so because of the click. The effect version fires whenever Coffee is shown while already in the cart, as it did for Tea.

A useful test: if a user could see this behavior without clicking anything, it is not an event. Sending a purchase request, showing a toast, navigating after submit and writing to analytics for a click are all event work.

On the other hand, something that really is "because this component is displayed", like logging a page view, is an effect. Under StrictMode it runs twice in development, which is fine: the log is for checking cleanup, and a production build runs it once.

4. Chains of effects

When one effect sets state that another effect depends on, you get a cascade: render, effect, render, effect, render. Each link is another full render, and the intermediate states are visible bugs waiting to happen.

JSX
// Chain: each effect triggers the next render
useEffect(() => { if (card?.gold) setGoldCardCount((c) => c + 1); }, [card]);
useEffect(() => { if (goldCardCount > 3) { setRound((r) => r + 1); setGoldCardCount(0); } }, [goldCardCount]);
useEffect(() => { if (round > 5) setIsGameOver(true); }, [round]);

Ask what actually starts this: the user places a card. So do all of it, in one pass, in the event handler, and derive what you can.

JSX
const isGameOver = round > 5; // derived, no state

function handlePlaceCard(nextCard) {
  if (isGameOver) {
    throw Error('Game already ended.');
  }
  setCard(nextCard);
  if (nextCard.gold) {
    if (goldCardCount < 3) {
      setGoldCardCount(goldCardCount + 1);
    } else {
      setGoldCardCount(0);
      setRound(round + 1);
    }
  }
}

All the updates happen in one batch, so React renders once with a consistent result. When the next state depends on several values or the transitions get complicated, put them in a reducer (useReducer and Reducers): a pure function is the easiest place to keep rules together.

The one legitimate chain is when state really depends on a network step you cannot do together, such as a dropdown for cities that must be fetched after the country changes. There, each fetch is a synchronization with a server and an effect is fine.

5. Notifying the parent

A child with a toggle must tell its parent when it changes. The beginner solution syncs through an effect on the child's own state.

Calling a parent callback: effect versus handler

Press the effect toggle once and compare the console with the handler toggle. The effect version renders the child (isOn = true), runs the effect, calls the parent's setter, and then renders the parent and both children again: two passes. Also look at what happened on mount: the effect called onChange(false) immediately and wrote effect false into the parent before anyone clicked. The handler version updates its own state and the parent's in one batched pass, with no mount-time call.

The inline onChange in the parent is a new function on every render, so it must be a dependency of the effect version, which makes the effect run after every parent render too. You can see the damage: switch the effect toggle ON, then press the handler toggle. The parent first says handler true, then the effect toggle's effect fires again because it received a new onChange, and the parent ends up saying effect true even though you clicked the other button. That is a bug the handler version cannot have.

Often the best design removes the duplicated state entirely: let the parent own the state and pass isOn and onChange down, making the child a controlled component (Lifting State Up and Sharing State).

6. Subscribing to an external store

Many beginners read an external value (something React does not own) in an effect and copy it into state. That works but takes manual cleanup and has an initial-flash problem. React provides useSyncExternalStore for this exact case: it reads the current value during render, subscribes, and re-renders when the store changes.

A tiny store read with useSyncExternalStore

Both StatusBar components update together from the same store, without effects, without local state and without a mismatch in the very first render. The browser's real network status (navigator.onLine plus the online and offline events) fits the same three functions. See External Stores and useSyncExternalStore for selectors and the details of why this hook exists.

7. One-time application setup

Code that must run once per application load (reading a config, starting an analytics library) does not belong in a component effect, because the effect belongs to the component's lifecycle: it can run again when the component is remounted, and StrictMode runs it twice on purpose.

JSX
// Wrong place: runs on every mount of App, twice in StrictMode development
function App() {
  useEffect(() => {
    loadDataFromLocalStorage();
    checkAuthToken();
  }, []);
}

// Better: top-level module code runs once per page load
if (typeof window !== 'undefined') {
  checkAuthToken();
  loadDataFromLocalStorage();
}

function App() {
  // ...
}

Keep module-level setup idempotent and cheap, and guard it with typeof window if the module is also imported on a server. If the work must happen after the app is displayed, an effect with a cleanup (or one that tolerates a repeat) is still right.

A decision guide

You want to... Use
Compute a value from props or state A plain const in render (add useMemo only if measured slow)
Reset all state when an identity changes A key on the component
React to a click, submit or key press An event handler
Update several pieces of state together One handler, or a reducer
Tell the parent something happened Call its callback in your handler, or lift state up
Read from an external, subscribable store useSyncExternalStore
Keep an outside system (timer, socket, widget, document title) in sync with what is on screen useEffect with cleanup
Fetch data because a component is shown An effect with cleanup for simple cases, a data library for real apps (Fetching Data)

When you review a component and see useEffect(() => { setSomething(...) }, [...]), treat it as a smell. About nine in ten of those can be turned into a calculation, a key or a handler. The remaining cases usually involve an external system, and they will want a cleanup function (Cleanup, Subscriptions and Timers).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A component stores fullName in state and updates it in an effect whenever first or last changes. What is the best fix?

    Values that can be calculated from props or state should not be state. Calculating in render is correct on the first paint and avoids the second render.
  2. 2. How do you reset all of a component's state when the userId prop changes?

    A changed key makes React discard the old instance and create a new one with fresh state, with no stale frame.
  3. 3. A toast should appear when the user clicks 'Add to cart'. Where does the code belong?

    The toast is caused by a user action. An effect would also fire on mount, on navigation back to an item already in the cart, and twice in StrictMode.
  4. 4. Why is useEffect(() => { onChange(isOn); }, [isOn, onChange]) in a child a poor way to inform the parent?

    The child renders, then the effect updates the parent, which renders everything again. Calling onChange in the handler batches both updates into one pass.
  5. 5. Which hook is the right tool for reading a value from a non-React store that can notify subscribers?

    useSyncExternalStore reads the current value during render, subscribes, and re-renders on change, without an effect that copies the value into state.

Summary

  • Effects synchronize a component with systems outside React. They are not for deriving values, reacting to user actions or wiring state together.
  • Calculate derived values during render; add useMemo only after measuring a slow calculation.
  • Reset state by changing a component's key, not by an effect that calls setters.
  • Put code that answers a user action in the event handler, and update several states in one handler or a reducer instead of a chain of effects.
  • Notify parents from the handler (or lift the state up), not from an effect on the child's own state.
  • Read external subscribable data with useSyncExternalStore, and run once-per-page setup at module level.

Next: Refs with useRef