Open In App
Related Articles

ReactJS useCallback Hook

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The useCallback hook is used when you have a component in which the child is rerendering again and again without need.

Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

Syntax:

const memoizedCallback = useCallback(
 () => {
   doSomething(a, b);
 },
 [a, b],
);

Creating React Application:

Step 1: Create a React application using the following command.

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command.

cd foldername

Project Structure: It will look like the following.

Without 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. Here, the filename is App.js

Javascript




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;


With useCallback hook: To solve this problem we can use the useCallback hook. Here, the filename is App.js.

Javascript




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);
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;


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.


Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 16 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials