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.
>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.