useCallback()
useCallback
hook in React.js is used to memoize functions, preventing them from being recreated on every render.useCallback
is a React Hook that lets you cache a function definition between re-renders.useCallback
will return a memoized version of the callback that only changes if one of the dependencies has changed.- This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g.
shouldComponentUpdate
).
useCallback(fn, deps)
Purpose
- using
useCallback()
we try to make better performance of the application only recreated when their dependencies change.
How to achieve the performance?
You can improve performance, particularly when passing callbacks to child components that rely on reference equality to prevent unnecessary renders.
- Passing Callbacks to Child Components: When a function is passed as a prop to a child component, and that component uses React.memo to avoid re-rendering unless props change.
- Avoiding Unnecessary Effects: When a function is used in an effect dependency array, useCallback can help avoid unnecessary re-executions of the effect.