Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React, useCallback updates a state variable that is also present in its dependency array, how does it prevent infinite re-rendering?

Consider the following code

import { useMemo, useState, useCallback } from 'react'


function App() {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    setCount(count + 1);

  }, [count]);

  return <div>
    <Child onClick={handleClick} />
  </div>
}


function Child({onClick}) {
  return (
    <button onClick={onClick}>Click here</button>
  )
}

export default App

In the above code, when the button with the text ‘Click here’ is clicked, the count state variable gets updated which is also a dependency in useCallback which is passed as a handler to onClick attribute of the button.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When count get changed by your handleClick, indeed now since count is a dependency of this useCallback, react will throw away the old handleClick and creates a new one in the new render that happened. So that’s it, a change in the dependency of a useCallback just throws away the old callback and gives you a new one..

Infinite renders on the other hand usually happen if you’re updating a state a in a useEffect that also has this state as deps. Example:

const [count, setCount] = useState(0);
useEffect(() => {
    setCount(count + 1);
}, [count]);  // this is bad, don't do it

So this is the distinction, a useEffect runs its body when the deps change, but useCallback does not run its body when the deps change, it just gives you a new function, and this new function can now see the new deps, in your case, the new handleClick will have access to the newest count state.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading