Use it to skip re-rendering
of components to optimize rendering performance.
In JavaScript, a function () {}
or () => {}
always creates a different function.
useCallback
becomes useful.useCallback
should wrap a function for render time difference.
function ProductPage({ productId, referrer, theme }) { // Tell React to cache your function between re-renders... const handleSubmit = useCallback((orderDetails) => { post('/product/' + productId + '/buy', { referrer, orderDetails, }); }, [productId, referrer]); // ...so as long as these dependencies don't change... return ( <div className={theme}> {/* ...ChildComponent will receive the same props and can skip re-rendering */} <ChildComponent onSubmit={handleSubmit} /> </div> ); }
On the initial render, useCallback
returns the callback function you have passed.
During subsequent renders, it will either return an already stored callback function
from the previous render (if the dependencies haven’t changed)
Or return a different callback function
you have passed during current render.