Skipping re-rendering of components to optimize rendering performance
In JavaScript, a function () {}
or () => {}
always creates a different function
useCallback
becomes usefulfunction 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> ); }
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.