Site icon MageComp Blog

ReactJS | useCallback Hook with Example

ReactJS useCallback Hook with Example

Hello ReactJS friends,

Till now, we have learned about various hooks in ReactJS. Today it’s the turn of useCallback hook in ReactJS.

React useCallback Hook

The React useCallback Hook returns a memoized callback function. Every callback function should be memoized to prevent the useless re-rendering of child components. This allows us to isolate resource-intensive functions so that they will not automatically run on every render. The useCallback Hook only runs when one of its dependencies updates. This can improve performance.

useCallback and useMemo hook are the same, but the only difference between the two is useMemo returns a memoized value and useCallback returns a memoized function.

Advantages of useCallback Hook in ReactJS:

Example of useCallback  Hook in ReactJS:

import React, { useCallback } from ‘react';
function MyComponent()
{
    const handleClick = useCallback(() =>
    {
        // handle the click event
    }, []);
    return <MyChild onClick={handleClick} />;
}

Conclusion:

Hope you understand the useCallback hook in ReactJS.

Learn other hooks in ReactJS

Stay in touch with us for more ReactJS tutorials.

Happy Coding!

Exit mobile version