今日已更新 133 条资讯 | 累计 29586 条内容
关于我们

React useDeepCompareEffect: Fix useEffect Object Dependencies (2026)

reactuse.com 2026年07月27日 11:05 5 次阅读 来源:Dev.to

React useDeepCompareEffect: Fix useEffect Object Dependencies (2026) You wire up a fetch. The endpoint takes a query object, so you pass it in the dependency array. The effect fires, sets state, the component re-renders, the query object is rebuilt — a brand-new object with identical contents — and the effect fires again. You have written an infinite loop, and React thinks it did exactly what you asked. function Results ({ term , page }: Props ) { const [ rows , setRows ] = useState ([]); const query = { term , page , sort : ' desc ' }; // new object, every render useEffect (() => { fetchRows ( query ). then ( setRows ); // setRows → re-render → new query → 🔁 }, [ query ]); } useDeepCompareEffect from @reactuses/core is a drop-in replacement for useEffect that compares dependencies by value instead of by reference. Same signature, same cleanup semantics — the effect just stops firing when nothing actually changed. Everything below is the real implementation, TypeScript-first, including the parts that cost you something. Why useEffect Can't See It React compares dependency arrays with Object.is , element by element. For primitives that's exactly what you want: 5 is 5 , 'desc' is 'desc' . For anything with an identity — objects, arrays, Date s, Map s, functions — it compares the reference , and a literal written inside a component body produces a fresh reference on every single render: Object . is ({ term : ' react ' }, { term : ' react ' }); // false — different objects So the dependency "changed" on every render, by React's definition. This isn't a bug in useEffect ; reference equality is the only comparison that's O(1), and React runs it on every render of every component. The cost of value comparison is real, and React declines to pay it on your behalf. Which leaves you paying it — one way or another. The Usual Workarounds, and Where They Fray Memoize the object. Correct, and the right answer when there's one dependency: const query = useMemo (() => ({ term , page

本文内容来源于互联网,版权归原作者所有
查看原文