flâneur — a map of the web's best reading

useCallback – React

react.dev · 4,002 words · saved by 1 readers

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