The useCallback
To understand the useCallback
hook first we will have to learn about memoisation what does it really mean?
Memoisation In computing, memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
Now let’s go back to the useCallback
hook.
useCallback
hook is nothing but it returns memoized callback function.
This hook helps us to prevent the function to recreate on every render, The function only recreates if one of its dependencies changes and returns the memoized function.
The useCallback hook is used when you have a component in which the child is rerendering again and again without need.
Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
Example
import { useCallback, useState } from 'react'
const Button = React.memo(({handleClick, name}) => {
console.log(`${name} rendered`)
return <button onClick={handleClick}>{name}</button>
})
const Counter = () => {
console.log('counter rendered')
const [firstCount, setFirstCount] = useState(0)
const [secondCount, setSecondCount] = useState(0)
const memoizedSetFirstCount = useCallback(() => setFirstCount(firstCount + 1), [firstCount)
const memoizedSetSecondCount = useCallback(() => setSecondCount(secondCount + 1), [secondCount])
return (
<>
{firstCount} {secondCount}
<Button handleClick={memoizedSetFirstCount} name="button1" />
<Button handleClick={memoizedSetSecondCount} name="button1" />
</>
)
}
When we click either of the buttons, we’ll only see the button we clicked to log into the console:
// counter rendered
// button1 rendered
// counter rendered
// button2 rendered
We’ve applied memoization to our button component, and the prop values that are passed to it are seen as equal. The two handleClick functions are memoized and will be seen as the same function by React until the value of an item in the dependency array changes (e.g. firstCount
, secondCount
).
Happy Coding 😊…