Let me give you a basic example:
const MeuComponente = () => {
const [counter, setCounter] = useState(0);
const incrementCounter = useCallback(()=>{
setCounter(counter + 1);
},[])
return (
<h1>{counter}</h1>
<button type="button" onClick={()=> incrementCounter()}>Incrementar</button>
)
}
export default MeuComponente;
In the above form without an array of dependencies, at the time React creates the function incrementCounter
the value of counter
is 0
.
Then when calling it at the click of the button, it is made the set of a new value being passed (counter + 1)
. Note that this counter
vale 0
, then the new value for counter
sera 1
.
But in the next clicks on the button when calling the increment function, the value of the counter variable inside remains 0, because this function was only created once with the use of useCallback, and the value contained in it is still that the counter was 0.
That is, from this no matter how many clicks you give on the button the counter value will always be displayed as 1, but within the function it is still 0.
This means that the counter value has not been updated inside the function.
To make the value inside be updated and reflect the real value, it is necessary to include it in the dependency array.
This causes the function to be updated and the values contained inside to be updated based on this dependency array.
const MeuComponente = () => {
const [counter, setCounter] = useState(0);
const incrementCounter = useCallback(()=>{
setCounter(counter + 1);
},[counter])
return (
<h1>{counter}</h1>
<button type="button" onClick={()=> incrementCounter()}>Incrementar</button>
)
}
export default MeuComponente;
Of course it is just an example, the ideal would be to do setCounter(Prev=> Prev + 1), this would avoid having to pass dependencies to useCallback.