Wonderjar's Blog

React SetState

2019-03-25

1
2
3
4
// Inside React DOM
const inst = new YourComponent();
inst.props = props;
inst.updater = ReactDOMUpdater;
1
2
3
4
5
// A bit simplified
setState(partialState, callback) {
// Use the `updater` field to talk back to the renderer!
this.updater.enqueueSetState(this, partialState, callback);
}

When use hooks,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// In React (simplified a bit)
const React = {
// Real property is hidden a bit deeper, see if you can find it!
__currentDispatcher: null,

useState(initialState) {
return React.__currentDispatcher.useState(initialState);
},

useEffect(initialState) {
return React.__currentDispatcher.useEffect(initialState);
},
// ...
};

Before render component

1
2
3
4
5
6
7
8
9
10
// In React DOM
const prevDispatcher = React.__currentDispatcher;
React.__currentDispatcher = ReactDOMDispatcher;
let result;
try {
result = YourComponent(props);
} finally {
// Restore it back
React.__currentDispatcher = prevDispatcher;
}

Tags: React