Without using the useCallback Hook
The problem is that once the counter is updated, all three functions are recreated again. The alert increases by three at a time but if we update some states all the functions related to that states should only re-instantiated. If another state value is unchanged, it should not be touched.
Example without the useCallback Hook:
This example creates a counter app without using the useCallback Hook.
Javascript
// Filename - App.js import React, { useState, useCallback } from 'react' ; const funccount = new Set(); const App = () => { const [count, setCount] = useState(0) const [number, setNumber] = useState(0) const incrementCounter = () => { setCount(count + 1) } const decrementCounter = () => { setCount(count - 1) } const incrementNumber = () => { setNumber(number + 1) } funccount.add(incrementCounter); funccount.add(decrementCounter); funccount.add(incrementNumber); alert(funccount.size); return ( <div> Count: {count} <button onClick={incrementCounter}> Increase counter </button> <button onClick={decrementCounter}> Decrease Counter </button> <button onClick={incrementNumber}> increase number </button> </div> ) } export default App; |
This example has a problem of re-rendering even when the props aren.t changed. This can be solved by using the useCallback Hook.
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