In React, when a component re-renders, all functions and data within the component are also re-evaluated. This can lead to performance issues, especially when dealing with expensive calculations or passing functions as props to child components.
When we change state our entire component re-render, So all the functions and data will be re-render.
We see useMemo for solve this problem but useMemo is not use when function call and passing value to function that time useCallback hook.
useMemo memorize value of function it means he give a return value not full function when useCallback return function.
const getItem = useMemo(() => {
return [number]
}, [number])
useEffect(() => {
setitems(getitems)
console.log('Updating Items')
}, [getitems])
const getItem = useCallback((n) => {
let num = number + n
return [num, num + 1, num + 2]
}, [number])
useEffect(() => {
setitems(getitems(5))
console.log('Updating Items')
}, [getitems])
Official React Docs says useCallback returns a memorized callback and useMemo returns a memorized value.
useMemo
vs useCallback
Before diving into useCallback
, let's briefly review useMemo
.
useMemo
useMemo
is used to memoize the result of expensive calculations, ensuring that the calculation is only performed when the dependencies change. It returns a memorized value.
const getItem = useMemo(() => {
return [number];
}, [number]);
useCallback
On the other hand, useCallback
is used to memoize functions, ensuring that the function reference remains the same between renders unless its dependencies change. It returns a memorized callback.
const getItem = useCallback((n) => {
let num = number + n;
return [num, num + 1, num + 2];
}, [number]);
useCallback
useCallback
is particularly useful when passing functions as props to child components, as it prevents unnecessary re-renders of the child components when the parent re-renders.
For example, consider the following scenario:
const ParentComponent = () => {
const handleClick = useCallback(() => {
// Handle click event
}, []);
return <ChildComponent onClick={handleClick} />;
};
In this example, handleClick
will retain the same reference between renders unless the dependencies specified in the dependency array change. This ensures that ChildComponent
does not re-render unnecessarily when ParentComponent
re-renders.
Using useCallback
can significantly improve the performance of your React applications, especially in scenarios where functions are passed as props to child components.
useCallback
Objective: Create a component that passes a memoized function as a prop to a child component and observe the performance improvements.
Create a Parent Component:
Define a parent component that includes a function to be memoized using useCallback
.
Create a Child Component:
Define a child component that receives the memoized function as a prop and renders it.
Observation:
Use React DevTools or any performance monitoring tool to observe the performance improvements achieved by using useCallback
.