I am studying react-hook recently. I have encountered a problem which makes me unable to understand in the process of practice.
import React, { useState, useCallback } from 'react';
const set = new Set();
function Demo() {
const [count, setCount] = useState(0);
const changeValue = useCallback(() => {
setCount(count + 1);
}, []);
set.add(count);
console.log('size: ', set.size);
return(
<div>
<p>Hello React Hook</p>
<p>{count}</p>
<button onClick={changeValue}>count++</button>
</div>
)
}
export default Demo;
// If you click the button multiple times, the output is:
// size: 1
// size: 2
// size: 2
I wrote a timer using react-hook. As I expected, the count value shown is always 1, because I didn't use count as a dependency of useCallback.
But what I can't understand is console.log('size: ', set.size)
only printed three times, why? Every time I click the count++
button, it will cause the Demo function to re-execute. So every time I click the button, shouldn't console.log('size: ', set.size)
will be executed? But in fact it only executed three times.
And why does size
keep 2 unchanged? I understand that setCount
will replace a new count
every time, so size
should not increase?
Please help me answer my doubts, thank you very much.
You can test my code here.