useCallback
useCallback
useCallback is a React hook that uses memoization to store/cache/remember a function provided to it.
The memoization happens by providing a dependency array, as long as all the values in the dependency array remain the same then the hook will return the stored function for that input set.
When they change it will process and store the new function for memoization.
This is a little different when compared against useMemo because useMemo remembers the value whereas useCallback remembers the actual function.
In React this comes in handy to prevent extra renders, and to allow functions to be defined within a component and still be passed into props or dependency arrays without causing excess re-renders.
Some context for this is that two identical functions are not actually identical because they have different signatures.
This means that each time a render in React happens, the function will be redefined with a new signature which will trigger a re-render everywhere that function is passed as a prop or in a dependency array.
The only way to prevent this is to use the exact same function so the signature is the same. There are a number of ways to do this and useCallback is one of those options.