What is useCallback hook in React js
“useCallback” is a react hook which is used for return the memorized version of callback function. If we want to optimize the performance by re-creation of the function then useCallback is useful.
Specially it is useful when we pass the props to a child component, if without usecallback we pass the props to child component react re-create that function on every render, unnecessary its re-render of child component but using the “useCallback” it re-render when the dependencies will change.
Syntax-:
const callbackValues = useCallback(() => {
// logic goes here
}, [Alldependencies]);
Alldependencies-: These are the arrays values if dependencies change then only function recreated
callbackValues-: It is the memories version of the function
Example:
Child.js
import React from "react";
function Child({ onClick }) {
console.log("re-rendered using callback");
return (
<div>
<button onClick={onClick}>Click Me Child Component</button>
</div>
);
}
export default Child;
App.js
import React, { useState, useCallback } from "react";
import Child from './Child'
function App() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Click Me Parent Component</button>
<Child onClick={increment} />
</div>
);
}
export default App;
Keep Learning 🙂