
Memoizing Everything Won't Speed Up React: useMemo, useCallback and the Compiler
- كاتب موثّق
- React 19
محتويات المقال
useMemo and every handler in useCallback, thirty changes in all. The React Profiler tells the same story before and after: each keystroke still re-renders the chart with thousands of points. Nothing in the chart's path checks whether its props are the same objects as last time, and one of those props is brand new on every render anyway.
The common misconception
What actually happens
A cache only helps someone who reads it
Object.is, then returns the cached value or recomputes it. useCallback(fn, deps) is effectively useMemo(() => fn, deps): your arrow function is still created on every render, and React hands back the old one when the dependencies match.
memo, and a value used as a dependency of another Hook, like useEffect. A stable handler on a <button> or on a child without memo changes nothing, because that child renders whenever its parent does. Caching a short string is pointless too, since strings already compare by value. And useMemo never speeds up the first render; it only skips work on updates.
Memoization is a chain
memo makes a component skip a render when every prop is Object.is-equal to the previous one. So the child must be wrapped in memo, and every prop must be stable. An inline object, an inline arrow or an array built in JSX is new on every render, and as the docs put it, a single always-new value is enough to break memoization for an entire component. All the other cached props feeding it are wasted.
import { useCallback, useMemo, useState } from "react";export function SalesPanel({ sales, region }: Props) { const [note, setNote] = useState(""); const title = useMemo(() => `Sales: ${region}`, [region]); const points = useMemo(() => toPoints(sales), [sales]); const onSelect = useCallback((id: string) => openSale(region, id), [region]); // ChartView isn't wrapped in memo: stable props change nothing return ( <> <textarea value={note} onChange={(e) => setNote(e.target.value)} /> <ChartView title={title} points={points} options={{ animate: false }} // a new object on every render onSelect={onSelect} /> </> );}import { memo, useCallback, useMemo, useState } from "react";const Chart = memo(ChartView); // skips renders when every prop is equalconst options = { animate: false }; // static: created onceexport function SalesPanel({ sales, region }: Props) { const [note, setNote] = useState(""); const title = `Sales: ${region}`; // strings compare by value const points = useMemo(() => toPoints(sales), [sales]); const onSelect = useCallback((id: string) => openSale(region, id), [region]); return ( <> <textarea value={note} onChange={(e) => setNote(e.target.value)} /> <Chart title={title} points={points} options={options} onSelect={onSelect} /> </> );}Chart is wrapped in memo, options is a module constant, points and onSelect are cached because a memo component receives them, and title is a plain string. Typing now re-renders SalesPanel and the textarea, and the chart skips its render. It also has one less Hook than the version that "memoized everything" and didn't work.
What React Compiler changes
babel-plugin-react-compiler Babel plugin, that analyzes components and Hooks and memoizes them for you. The docs say it applies the equivalent of memo to every component, and that its memoization is in most cases as precise as handwritten code, or more. It works best with React 19 and also supports React 17 and 18.
eslint-plugin-react-hooks report. For new code, the docs recommend letting the compiler memoize and keeping useMemo and useCallback as escape hatches for precise control, such as a value used as an Effect dependency. For existing code, leave the memoization in place or test carefully before removing it, because removing it can change what the compiler outputs.
memo component, a dependency array or a slow calculation uses the cache | |
useCallback avoids creating the function | |
memo for the whole component | |
useMemo speeds up the first render | |
useMemo |
How to apply it in your project
Profile the slow interaction first Record it in the React DevTools Profiler, ideally on a production build with CPU throttling. Look for an expensive component that renders with the same props; that's the only place memocan help.Complete the chain where it matters Wrap that component in memo, then make every prop stable: hoist constants out of the component, pass primitives instead of objects, and cache the rest withuseMemoanduseCallback.Remove memoization nobody reads Without the compiler, delete useCallbackon handlers for DOM elements or children withoutmemo, anduseMemoaround cheap strings and numbers. The code gets shorter and nothing gets slower.Turn on React Compiler Install babel-plugin-react-compilerfirst in your Babel pipeline, or use your framework's option, and enable therecommendedpreset ofeslint-plugin-react-hooksto see what it skips. Compiled components show a "Memo" badge in React DevTools.
Key takeaways
useMemoanduseCallbackonly pay off when amemocomponent, a dependency array or a slow calculation uses the cached value.Memoization is a chain: the child needs memoand every prop must be stable, and one new object breaks it.Keeping state local and passing JSX as childrenoften removes the need for memoization entirely.React Compiler 1.0 memoizes components and Hooks at build time; write new code plainly and keep the Hooks as escape hatches.
التعليقات (0)