How to use React useCallback Hook In ReactJS
To solve this problem we can use the useCallback hook.
React useCallback Hook Example:
This example demonstrate the use of useCallback Hook.
Javascript
// Filename - App.js import React, { useState, useCallback } from "react" ; var funccount = new Set(); const App = () => { const [count, setCount] = useState(0); const [number, setNumber] = useState(0); const incrementCounter = useCallback(() => { setCount(count + 1); }, [count]); const decrementCounter = useCallback(() => { setCount(count - 1); }, [count]); const incrementNumber = useCallback(() => { setNumber(number + 1); }, [number]); funccount.add(incrementCounter); funccount.add(decrementCounter); funccount.add(incrementNumber); return ( <div style={{ display: "flex" , flexDirection: "column" , textAlign: "center" , justifyContent: "end" , margin: "auto" , marginTop: "20px" , width: "350px" , padding: "50px" , height: "300px" , fontSize: "20px" , boxShadow: "0px 2px 8px 4px grey" , borderRadius: "5px" , }} > { " " } <h2 style={{ color: "green" }}> w3wiki </h2> <h4>React Example for useCallback Hook</h4> <p>Count: {count}</p> <p>Function Count: {funccount.size}</p> <button onClick={incrementCounter}> Increase counter </button> <button onClick={decrementCounter}> Decrease Counter </button> <button onClick={incrementNumber}> Increase number </button> </div> ); }; export default App; |
Output: As we can see from the below output when we change the state ‘count’ then two functions will re-instantiated so the set size will increase by 2 and when we update the state ‘number’ then only one function will re-instantiated and the size of the set will increase by only one.
React useCallback Hook
React useCallback hook returns a memoized function to reduce unnecessary callbacks. This useCallback hook is used when you have a component in which the child is rerendering again and again without need.
Table of Content
- React useCallback Hook
- React useCallback Hook Usage
- Without using the useCallback Hook
- Using React useCallback Hook
Contact Us