useCallback – React
Call useCallback at the top level of your component to cache a function definition between re-renders: See more examples below. fn: The function value that you want to cache. It can take any arguments and return any values. React will return (not call!) your function back to you during the initial render. On next renders, React will give you the same function again if the dependencies have not changed since the last render. Otherwise, it will give you the function that you have passed during the current render, and store it in case it can be reused later. React will not call your function. The function is returned to you so you can decide when and whether to call it. dependencies: The list of all reactive values referenced inside of the fn 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
API Reference Hooks Copy page Copy useCallback useCallback is a React Hook that lets you cache a function definition between re-renders. const cachedFn = useCallback ( fn , dependencies ) Note React Compiler automatically memoizes values and functions, reducing the need for manual useCallback calls. You can use the compiler to handle memoization automatically. Reference useCallback(fn, dependencies) Usage Skipping re-rendering of components Updating state from a memoized callback Preventing an Effect from firing too often Optimizing a custom Hook Troubleshooting Every time my component renders
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
- useMemo – Reactreact.dev
- You Might Not Need an Effect – Reactreact.dev
- Blogged Answers: A (Mostly) Complete Guide to React Rendering Behavior · Mark's Dev Blogblog.isquaredsoftware.com
- Why React Re-Renders • Josh W. Comeaujoshwcomeau.com
- How to write performant React code: rules, patterns, do's and don'ts | Developer Waydeveloperway.com
- Hooks, Dependencies and Stale Closurestkdodo.eu
- React re-renders guide: everything, all at once | Developer Waydeveloperway.com
- When does React re-render components? | Felix Gerschaufelixgerschau.com
- useEffect – Reactreact.dev
- Implementing React from scratchrob.directory