useCallback hook is one of the best hooks offered by react. It’s widely used to memoize a function, so that expensive calculations are not performed when we do not need them. It could be and is often, easily confused with the useMemo hook. import {useCallback} from ‘react’;
const expensiveFunction= useCallback(function,[dependency list])
//function is the function to be memoized.
//dependency list is the list of parameters, any change in them would make the function run again.
It is to be noted that, expensiveFunction will hold the cached function
and not run unless the values of parameters in dependency list change .
Through with the basics; let’s see useCallback in action. Following attached is the code of a parent component (App) having a child component (Child). App has a button to toggle theme of the div. An input to get the length of random number to be generated, and a button to generate random number. Child is a simple component which fetches the random number and displays it.import { useState, useCallback } from “react”;
import Child from “./Child”;
import “./styles.css”;
const App = () => {
const [isDark, setDark] = useState(false);
const [input, setInput] = useState(0);
//uncomment this to view functionality of useCallback
// const randomNumber = useCallback(() => {
// return Math.floor(Math.random() * Math.pow(10, input));
// }, [input]);
const randomNumber = () => {
return Math.floor(Math.random() * Math.pow(10, input));
};
return (
<div className={isDark ? “dark” : “light”}>
<input
className=”inputBox”
onChange={(e) => setInput(e.target.value)}
placeholder=”Enter the length of random number”
/>
<Child randomNumber={randomNumber} />
<button onClick={() => setDark(!isDark)}>Toggle Theme</button>
</div>
);
};
export default App;import { memo } from “react”;
const Child = ({ randomNumber }) => {
console.log(“Child”);
return (
<>
<h1>{randomNumber()}</h1>
</>
);
};
//uncomment this to implement memoization.
// export default memo(Child);
export default Child;
Run the above code yourself, for better understanding:
As you must have noticed, we get the log every time we press Toggle Theme, it’s undesired as it’s not connected to child. Hence to overcome, one might think of using memo. The thought is partially valid. Each time toggle button is pressed, isDark changes, and hence the component re renders. Every time the component renders all the functions/values are re created. Although the new functions/values are same, but their references with respect to the functions/values before the render are different. As, react uses referential equality to detect the change, it detects a change and hence the Child is rendered. Hence, memo would be of little use.
Thus, to overcome this behaviour useCallback hook is used. It helps the react to maintain the referential equality, by only executing a function when the dependency is changed. If not changed, an already memoized value of function is returned.