الانتقال إلى المحتوى
FrontendReact· 7 دقائق للقراءة

You Probably Don't Need That Effect: Derived State and Event Logic

Calculate what you can during render, and run what the user caused in the handler that caught it.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

Two bug reports arrive from the shop on the same day. The first: "I removed a pair of shoes from my cart and it said 'Added to cart'." The second: "That toast also pops up every time I open the cart page." Both come from one innocent Effect that shows the toast whenever the cart's items change. Right above it sits another Effect that recalculates the total the same way. Neither one talks to anything outside React, and that's the real problem.

The common misconception

The belief: when some state changes and something else should follow, an Effect is the place for it. Items changed? An Effect updates the total. The cart grew? An Effect shows a toast. The dependency array reads like a list of triggers: "when this changes, do that".

It's an easy habit to form. Effects are the one Hook whose job sounds like "run code when something changes", and writing the Effect keeps every reaction in one tidy place. In a class component, componentDidUpdate was where you compared old and new values and acted on the difference, so the pattern feels familiar. And it works, in the sense that the screen ends up right. The costs show up as extra renders, a value that's briefly stale, and logic that fires for reasons nobody intended.

What actually happens

Ask two questions before writing an Effect

React's docs call an escape hatch: they're for synchronizing with a system outside React, like a network connection, a browser API or a non-React widget. If there's no outside system, you usually don't need one. When you're not sure, ask why the code needs to run. If it's because the component is now on screen, an Effect fits. If it's because the user clicked, typed or submitted something, the code belongs in that event's handler.

Derived values: calculate, don't store

A total, a filtered list or a full name made of two fields is : it can be calculated from props or existing state. React's docs are blunt about it: if you can calculate it during rendering, don't put it in state. Copying it into state with an Effect costs a full extra pass. React renders the component and its children with the old total, commits, runs the Effect, which sets the new total, and renders everything again. You also now have two sources of truth that only agree after the Effect has run.

Calculated in the component body, the total is recomputed on every render from the current items, so it's never stale and needs no dependency list. If the calculation is genuinely slow, wrap it in useMemo, which caches the result until its inputs change. It's still a calculation during render, not an Effect.

Event logic: let the cause decide

An Effect only sees state after the fact. It knows that items changed, not whether the user added an item, removed one, or just opened a page with a saved cart. That's why the toast lies. The message belongs to one specific action, so it goes in that action's handler, where the cause is known:

TSX Cart.tsx
import { useEffect, useState } from "react";type Item = { id: string; price: number };export function Cart({ initialItems }: { initialItems: Item[] }) {  const [items, setItems] = useState(initialItems);  const [total, setTotal] = useState(0);  // Derived data copied into state: an extra render, briefly stale  useEffect(() => {    setTotal(items.reduce((sum, item) => sum + item.price, 0));  }, [items]);  // Sees "items changed", not what the user did  useEffect(() => {    if (items.length > 0) showToast("Added to cart");  }, [items]);  function add(item: Item) {    setItems([...items, item]);  }  function remove(id: string) {    setItems(items.filter((item) => item.id !== id));  }  return <CartView items={items} total={total} onAdd={add} onRemove={remove} />;}

The right version has one state variable instead of two and no Effects. Removing an item can't show "Added to cart" any more, because only add shows it, and opening the page shows nothing because no handler ran. Code caused by the component being on screen, like logging a page view, is still a fine Effect. Code caused by a click is not.

Store less, derive the rest

Many "sync" Effects exist because state holds a copy of something. A classic one clears the selection when the list changes: useEffect(() => setSelected(null), [orders]). React's guide on state structure suggests storing only the selected id and finding the item during render with orders.find((o) => o.id === selectedId) ?? null. The selection then follows the latest data and becomes null by itself when the order disappears. The same goes for props: copying a prop into state freezes its first value. Use the prop directly, or name it initialItems, as above, when ignoring later values is the point.

You wrote an Effect that…Do this instead
Sets state calculated from other props or stateCalculate it during render; useMemo if it's measurably slow
Resets all of a component's state when a prop changesGive the component a key
Clears or fixes a selection when the list changesStore the selected id and derive the item
Reacts to state a click just set: a toast, a POST, navigationDo it in that click's event handler
Calls a parent's onChange after local state changesCall it in the same handler that sets the state

How to apply it in your project

  1. Find Effects that only call settersSearch for useEffect bodies that just call setSomething from other props or state, or let the set-state-in-effect rule in the recommended eslint-plugin-react-hooks preset flag them. Each is a candidate for a calculation in render, a key, or an id instead of a copy.
  2. Ask why each Effect runsIf the honest answer is "because the user clicked, typed or submitted", move the code to that handler. Keep the Effect only if the answer is "because this is on screen" or "to stay in sync with something outside React".
  3. Shrink state to the minimumStore ids instead of copied objects, drop state that mirrors props, and merge values that always change together. Less state means fewer things to keep in sync.
  4. Measure before reaching for useMemoUnless you're creating or looping over thousands of objects, a calculation in render is rarely expensive. Add useMemo where a measurement says so, or let React Compiler handle it.

Key takeaways

  • If a value can be calculated from props or state, calculate it during render instead of copying it with an Effect.
  • Effects see that state changed, not why; code caused by a user action belongs in that action's handler.
  • Store the minimum state, like ids instead of copies, and reset whole components with a key rather than an Effect.
  • Keep Effects for synchronizing with systems outside React, such as sockets, widgets and browser APIs.

📚 المصادر

  1. You Might Not Need an Effect — React
  2. Choosing the State Structure — React
  3. Separating Events from Effects — React
  4. useMemo — React API Reference
  5. set-state-in-effect — eslint-plugin-react-hooks

التعليقات (0)