4 ms·
> setState mutates some “global” state Is this true? Maybe I'm reading it wrong but this.setState in a React.Component just transparently calls out to `this.up
by gcommer 8y ago
> setState mutates some “global” state
Is this true? Maybe I'm reading it wrong but this.setState in a React.Component just transparently calls out to `this.updater`[1] where `this.updater` is injected by the particular platform library (eg react-dom). At least in react-dom/server's case, a unique `updater` object exists per-component[2], so it's effectively a private instance field; and those state changes apply to a similarly per-component `inst.state`[3]
You can also prove this by calling setState with the wrong `this`: `this.setState.call({}, {x:1})` blows up. So the `this` is required, unlike how `useState` works.
[1]: https://github.com/facebook/react/blob/aa9423701e99a194d65a8b835882502902a65a50/packages/react/src/ReactBaseClasses.js#L66 https://github.com/facebook/react/blob/aa9423701e99a194d65a8...
[2]: https://github.com/facebook/react/blob/aa9423701e99a194d65a8b835882502902a65a50/packages/react-dom/src/server/ReactPartialRenderer.js#L426 https://github.com/facebook/react/blob/aa9423701e99a194d65a8...
[3]: https://github.com/facebook/react/blob/aa9423701e99a194d65a8b835882502902a65a50/packages/react-dom/src/server/ReactPartialRenderer.js#L607 https://github.com/facebook/react/blob/aa9423701e99a194d65a8...
- baddox 8y agoI actually don’t know that much about the implementation, but it sounds like you’re right. I believe I was recalling this article by Dan Abramov: https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889 https://medium.com/@dan_abramov/making-sense-of-react-hooks-... (Ctrl-f “where React keeps the state for Hooks”) Which is talking about where the state is stored, not the implementation detail of how setState works.