useMemo – React
calculateValue: The function calculating the value that you want to cache. It should be pure, should take no arguments, and should return a value of any type. React will call your function during the initial render. On next renders, React will return the same value again if the dependencies have not changed since the last render. Otherwise, it will call calculateValue, return its result, and store it so it can be reused later. dependencies: The list of all reactive values referenced inside of the calculateValue code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is configured for React, it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like [dep1, dep2, dep3]. React will compare each dependency with its previous value using the Object.is comparison. On the initial render, useMemo retur
API Reference Hooks Copy page Copy useMemo useMemo is a React Hook that lets you cache the result of a calculation between re-renders. const cachedValue = useMemo ( calculateValue , dependencies ) Note React Compiler automatically memoizes values and functions, reducing the need for manual useMemo calls. You can use the compiler to handle memoization automatically. Reference useMemo(calculateValue, dependencies) Usage Skipping expensive recalculations Skipping re-rendering of components Preventing an Effect from firing too often Memoizing a dependency of another Hook Memoizing a function Troub
Explore this link on the map →related reading
- Understanding useMemo and useCallback • Josh W. Comeaujoshwcomeau.com
- What is Memoization? How and When to Memoize in JavaScript and Reactfreecodecamp.org
- useCallback – Reactreact.dev
- You Might Not Need an Effect – Reactreact.dev
- Why React Re-Renders • Josh W. Comeaujoshwcomeau.com
- Blogged Answers: A (Mostly) Complete Guide to React Rendering Behavior · Mark's Dev Blogblog.isquaredsoftware.com
- React re-renders guide: everything, all at once | Developer Waydeveloperway.com
- How to write performant React code: rules, patterns, do's and don'ts | Developer Waydeveloperway.com
- Pure components in React: Using PureComponent and React.memo - LogRocket Blogblog.logrocket.com
- When does React re-render components? | Felix Gerschaufelixgerschau.com
- Hooks, Dependencies and Stale Closurestkdodo.eu
- The Interactive Guide to Rendering in Reactui.dev