Techcookies

Understanding useCallback hook of ReactJS

ReactJS, JavaScript | Tue Apr 19 2022 | 1 min read

useCallback hook helps create memorized callback.

useCallback hook is used to improve our component's performance.

useCallback prevents unnecessary re-rendering of child component by returning the same instance of the function that is passed instead of creating a new once each time.

If a parent component with a state variable and we want to update that state from a child component. we choose to pass down a callback function to the child from the parent component. This allows us to update the state in the parent component.

useCallback memoizes our callback functions, so they not recreated on every re-render. Using useCallback correctly can improve the performance of our app significantly.

js
//UseCallbackHook -- parent component
import React, {useCallback, useState} from 'react';
import UseCallbackHookChild from './useCallbackHookChild';
const UseCallbackHook = () => {
    const [data, setData]=useState(['Product1', 'Product2']);
    const addData=useCallback(()=>{
        setData([...data, `Product${data.length+1}`]);
    },[data]);
    return (
        <UseCallbackHookChild data={data} addData={addData} />
    )
}
export default UseCallbackHook;



//UseCallbackHookChild -- child component
import React from 'react';

const UseCallbackHookChild = ({data, addData}) => {
    return (
        <>
            {data && data.map((element) => {return element})}
           
            <button onClick={addData}>Add data</button>
        </>
    )
}
export default UseCallbackHookChild;

Code: https://github.com/madhukarjha/reactHooks/blob/master/src/components/UseCallbackHook.js