
You Probably Don't Need That Effect: Derived State and Event Logic
- كاتب موثّق
- React 19
محتويات المقال
The common misconception
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
Derived values: calculate, don't store
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
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:
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} />;}import { useState } from "react";type Item = { id: string; price: number };export function Cart({ initialItems }: { initialItems: Item[] }) { const [items, setItems] = useState(initialItems); // Calculated during render: always matches items, no extra pass const total = items.reduce((sum, item) => sum + item.price, 0); function add(item: Item) { setItems([...items, item]); showToast("Added to cart"); // caused by this click, so it lives here } function remove(id: string) { setItems(items.filter((item) => item.id !== id)); } return <CartView items={items} total={total} onAdd={add} onRemove={remove} />;}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
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.
useMemo if it's measurably slow | |
key | |
onChange after local state changes |
How to apply it in your project
Find Effects that only call setters Search for useEffectbodies that just callsetSomethingfrom other props or state, or let theset-state-in-effectrule in the recommendedeslint-plugin-react-hookspreset flag them. Each is a candidate for a calculation in render, akey, or an id instead of a copy.Ask why each Effect runs If 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". Shrink state to the minimum Store 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. Measure before reaching for useMemo Unless you're creating or looping over thousands of objects, a calculation in render is rarely expensive. Add useMemowhere 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 keyrather than an Effect.Keep Effects for synchronizing with systems outside React, such as sockets, widgets and browser APIs.
التعليقات (0)