useMemo and useCallback: when are they actually worth it?
posée 4 months ago88 vuesen
A teammate wraps every function in useCallback and every computed value in useMemo. Is that a good practice or premature optimization?
Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
2 réponses
Mostly premature. Memoization has its own cost (memory, comparing dependencies, noisier code). Use it when there's a concrete reason:
1. Expensive computation: e.g. filtering or sorting thousands of rows each render. Use useMemo. 2. Referential stability matters: the value or function is passed to a React.memo child, or used in another hook's dependency array.
const visible = useMemo(() => rows.filter(matches(query)), [rows, query]);
If neither applies, skip it. With the React Compiler (stable in React 19+ setups), components are memoized automatically, and manual useMemo/useCallback become mostly unnecessary.
Connectez-vous pour dire si ça a marché.
Measure first. Open the React DevTools Profiler, record the slow interaction, and see which components re-render and how long they take. Optimize the ones that show up there, not everything.
Connectez-vous pour dire si ça a marché.
Sign in and verify your email to post an answer.