How the useCallback hook works


useCallback
hook is used for performance optimization and to cache something.
When do we use useCallback
?
It is used to freeze a function reference.
See, whenever a component renders, all the functions of the component are created.
Therefore, when a component re-renders, the functions are also re-created.
Now, if you have a function that performs expensive operations ( such as requiring a lot of time or space or resources), then re-creating it with every re-render affects the app performance. To avoid it, you use useCallback
.
A catch to catch
The useCallback
hook does not stop the function from executing if called. It only stops it from being recreated.
Syntax
const func = useCallback(() => resource extensive function definition, [dependencies])
useCallback takes 2 arguments:-
First is the actual function definition
Second is the dependency array, on the change of which the function is to be re-created.
Note
If you don't include a reactive value (like states, props, or variables) used in the useCallback function in the dependency array, the function will only use its original value and not the updated one.
With the help of useCallback
, you can also avoid unnecessary re-renders of child components that take in the callback function as props.
This is because without useCallback
The function is recreated on component re-render → the reference to the function changes → the prop of the child component changes → the child component re-renders.
And with useCallback
The function is not recreated on component re-render (unless the dependencies change) → the reference to the function does not change → the prop of the child component does not change → the child component does not re-render.
React.memo
If a child component receives a value prop instead of a function, use React.memo
in the child component to prevent re-renders when the prop value remains unchanged.
How, you ask?
The below code sample shows how you can implement React.memo
in the child component.
const childComponent = React.memo((props) => {
return <></>
})
With this, the childComponent
will not re-render with every change in the parent component, but only when there is a change in the value of the respective prop being passed to it.
Hope you liked and understood it!
Happy callbacking! :)
Subscribe to my newsletter
Read articles from Riya Agarwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
