
useEffect Is Not a Lifecycle Method: Think in Synchronization
- كاتب موثّق
- React 19
محتويات المقال
PriceTicker that shows a live price for the selected symbol. Pick AAPL, then switch to TSLA: the label says TSLA, but the number keeps moving with Apple's price. The Effect inside was written as "subscribe on mount", with [] and a comment that silences the linter, because the author only wanted to subscribe once. It did exactly that: once, for the first symbol it ever saw.
The common misconception
useEffect is the Hooks version of the class lifecycle methods. [] means componentDidMount, the returned function is componentWillUnmount, and the dependency array is a list you pick to decide when the code fires: "run this when X changes, but not when Y does".
[], an Effect does run only after the first commit, and React's own docs, looking from the component's side, describe that as running on mount. But that view tells you when the code runs, not what it's for. And once you treat the array as a schedule, a linter that disagrees with you starts to look like noise.
What actually happens
An Effect keeps one outside thing in sync
Dependencies describe the code, not a schedule
Object.is. If one changed, React runs the previous cleanup with the old values, then setup with the new ones.
exhaustive-deps lint rule checks it. So [] doesn't mean "once". It's a claim: this Effect reads nothing that can change between renders. When the claim is true, the Effect runs after the first commit and cleans up when the component unmounts. When it's false, the Effect keeps working with the values from the render where it last ran.
Re-synchronizing: stop the old, start the new
import { useEffect, useState } from "react";export function PriceTicker({ symbol }: { symbol: string }) { const [price, setPrice] = useState<number | null>(null); // "componentDidMount": subscribe once, never look back useEffect(() => { subscribeToPrice(symbol, setPrice); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return <p>{symbol}: {price ?? "…"}</p>;}import { useEffect, useState } from "react";export function PriceTicker({ symbol }: { symbol: string }) { const [price, setPrice] = useState<number | null>(null); // Keep one subscription in sync with the symbol on screen useEffect(() => { const unsubscribe = subscribeToPrice(symbol, setPrice); return unsubscribe; // stop syncing the old symbol before the next one }, [symbol]); return <p>{symbol}: {price ?? "…"}</p>;}setPrice.
price still holds Apple's last number. Rendering <PriceTicker key={symbol} symbol={symbol} /> resets it, as an earlier article in this path showed.
Strict Mode's extra cycle tests the model
[] means "run on mount" | [] means "this Effect reads no props or state" |
componentWillUnmount | |
How to apply it in your project
Turn on the lint and delete the suppressions Enable react-hooks/exhaustive-depsand search for comments that disable it. Each one marks an Effect that may be reading stale values; change the code until the linter agrees.Name the system behind every Effect For each Effect, write down which outside thing it keeps in sync: a socket, a listener, a widget, a timer. If there's no outside system, it probably shouldn't be an Effect; the next article covers what to do instead. Write cleanup that mirrors setup Subscribe and unsubscribe, connect and disconnect, setIntervalandclearInterval, add and remove a listener. If you can't undo the setup, that's the bug to fix first.Keep Strict Mode on Treat doubled connections or listeners in development as missing cleanup, not as React being strange.
Key takeaways
An Effect synchronizes one outside system with the current render: setup starts it, cleanup stops it. Dependencies list every reactive value the Effect reads; change them by changing the code, not by editing the array. []isn't "on mount" but a claim that the Effect reads nothing reactive; when that's false, it runs with stale values.Strict Mode's extra setup and cleanup is a test: if a user could notice it, the cleanup is missing.
التعليقات (0)