HomeToolsAbout a20k

useCallback

What is it

Skipping re-rendering of components to optimize rendering performance

  • Caching the functions that you pass to child components

In JavaScript, a function () {} or () => {} always creates a different function

  • this is where useCallback becomes useful
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}> {/* ...ShippingForm will receive the same props and can skip re-rendering */} <ShippingForm onSubmit={handleSubmit} /> </div> ); }

Return Value

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 last render (if the dependencies haven’t changed), or return the callback function you have passed during this render.

© VincentVanKoh