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
related reading
- useMemo – Reactreact.dev
- Understanding useMemo and useCallback • Josh W. Comeaujoshwcomeau.com
- You Might Not Need an Effect – Reactreact.dev
- What is Memoization? How and When to Memoize in JavaScript and Reactfreecodecamp.org
- Why React Re-Renders • Josh W. Comeaujoshwcomeau.com
- Blogged Answers: A (Mostly) Complete Guide to React Rendering Behavior · Mark's Dev Blogblog.isquaredsoftware.com
- useEffect – Reactreact.dev
- Build your own Reactpomb.us
- When does React re-render components? | Felix Gerschaufelixgerschau.com
- Implementing React from scratchrob.directory
- React useRef Hook By Example: A Complete Guidelearnreact.design
- ALL React Hooks Explained in 12 Minutesyoutube.com