How to use React useCallback hook with examples
In this tutorial, we are going to learn about how to use react useCallback
hook and advantages of using useCallback
hook with examples.
useCallback() hook
The useCallback()
hook helps us to memoize the functions so that it prevents the re-creating of functions on every re-render.
The function we passed to the useCallback
hook is only re-created when one of its dependencies are changed.
Let’s see an example:
import React, {useState} from "react";
import ReactDOM from "react-dom";
function Button(props) {
return <button onClick={props.onClick}>{props.name}</button>;}
function App() {
const [count, setCount] = useState(0);
const [isActive, setActive] = useState(false);
const handleCount = () => setCount(count + 1); const handleShow = () => setActive(!isActive);
return (
<div className="App">
{isActive && ( <div> <h1>{count}</h1> <Button onClick={handleCount} name="Increment" /> </div> )} <Button onClick={handleShow}
name={isActive ? "Hide Counter" : "Show Counter"}
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
In the above code, we have two functions which are (handleCount, handleShow) and the problem is every time if we click on any button
UI is updated and two functions are re-created again.
To solve this problem we need to wrap our functions with useCallback
hook.
import React, { useState, useCallback } from "react";
import ReactDOM from "react-dom";
function Button(props) {
return <button onClick={props.onClick}>{props.name}</button>;
}
function App() {
const [count, setCount] = useState(0);
const [isActive, setActive] = useState(false);
const handleCount = useCallback(() => setCount(count + 1), [count]); const handleShow = useCallback(() => setActive(!isActive), [isActive]);
return (
<div className="App">
{isActive && (
<div>
<h1>{count}</h1>
<Button onClick={handleCount} name="Increment" />
</div>
)}
<Button
onClick={handleShow}
name={isActive ? "Hide Counter" : "Show Counter"}
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
Here wrapped our two functions with useCallback
hook and second argument is a dependency, so that
functions are only re-created if one of its dependency value is changed.
Now, If we click on Increment
button count
value is changed and handleCount
function is re-created.