reactjs(useCallback Hook)

useCallback(fn, dependencies)

parameters:

Pass a function and the list of dependencies.

Returns:

It returns a memoized/cached copy of function passed to it, and only changes if one of the dependencies changes.

Call useCallback hook at the top level of your component to cache a function definition between re-renders:

lets understand the useCallback hook from below sample code:

// sample code starts here...

import { useCallback } from 'react';

export default function ProductPage({ productId, referrer, theme }) {

// In below line of code we are passing orderdetails function inside the usecallback hook, and second we are passing dependency/dependencies.

const handleSubmit = useCallback((orderDetails) => {

post('/product/' + productId + '/buy', {

referrer,

orderDetails,

});

}, [productId, referrer]);

// sample code ends here..

In other words, useCallback caches a function between re-renders until its dependencies change.

Let’s walk through an one more sample code to see when it's useful.

Here we are passing a handleSubmit function down from the ProductPage to the ShippingForm component:

function ProductPage({ productId, referrer, theme }) {

// once we pass orderdetails function to useCallback Hook as in below line of code, it tell React to cache your function between re-renders as long the dependencies pass are same.

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>

);

}

In above sample code, by wrapping handleSubmit in useCallback, you ensure that it’s the same function between the re-renders (until dependencies change(compared with object.is )). You don’t have to wrap every function in useCallback unless you do it for some specific reason. In this example, the reason is that you pass it to a component wrapped in memo(as shown below), and this lets it skip re-rendering.

// below is the ShippingForm functional component which is wrapped in memo.

import { memo } from 'react';

const ShippingForm = memo(function ShippingForm({ onSubmit }) {

// ..sample code line 1

// ..sample code line 2

});

// Article ends here..

Thanks, Happy coding