Closed
Description
Hello, I'm confused about how useState and setState work, for a simple example:
import React, { useState } from 'react';
const globalLog = console.log.bind(window);
function App() {
const [count, setCount] = useState(0);
function handleClick() {
setCount((c) => {
console.log('local log');
globalLog('global log');
return c + 1;
});
}
return (
<div className="App">
<p>{count}</p>
<button onClick={handleClick}>add</button>
</div>
);
}
You can use this prepared code example:https://codesandbox.io/s/goofy-sea-6evwt?file=/src/App.js
React StrictMode:
- On the first click,
local log
andglobal log
print once each. - On the second click,
local log
prints once, butglobal log
prints twice. - Third,fourth..., same as the second time
General mode:
- On the first click,
local log
andglobal log
print once each. - Second,third,fourth..., same as the second time.
And I know React uses a cycle linked-list to store the updater,and call all updaters in a loop during the update phase the source code,
So in strict mode, what does React do to the 'local' console.log
and why does it only print once.
Is this a bug or a question ?
Metadata
Assignees
Labels
No labels