(And of course, there's the magic of the returned object not being set as the new state, but rather being merged into the previous one.)
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/aa9423701e99a194d65a8... [2]: https://github.com/facebook/react/blob/aa9423701e99a194d65a8... [3]: https://github.com/facebook/react/blob/aa9423701e99a194d65a8...
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.
At least from the principle of least surprise, Hooks don't have that particular learning hump of trying to use a built-in language feature (class instance variables) and finding out the hard way that they don't work as expected.
I thought it updates the state and the re-render is what is included in a scheduled function?
> it's best practice to provide an updated function rather than a plain object
I'm guessing you mean for a global store with shared state? Local components aren't singletons.
See here: https://reactjs.org/docs/react-component.html#setstate
> setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state.
(Emphasis mine.)
> I'm guessing you mean for a global store with shared state? Local components aren't singletons.
No, local state, the one you set using `setState`. The offical docs don't actually recommend always using an updater function, but it's the primary method they explain, and my inclination is to better be safe than sorry:
> If the next state depends on the current state, we recommend using the updater function form, instead