dillon1000/react
Commit
Browse files Set state takes a function
This diff enables setState to accept a function in addition to a state partial. If you provide a function, it will be called with the up-to-date `state, props, context` as arguments.
This enables some nicer syntax for complex setState patterns:
If setState is doing an increment and wants to guarantee atomicy, you need a function:
```
this.setState(state => ({ number: state.number + 1 }));
```
This atomicy is particularly important if setState is called multiple times in a single frame of execution as the result of complex user actions. It's a tricky bug to chase down and difficult to determine how to fix when you find it. The current pattern of reaching into _pendingState relies on an implementation detail.
In this example: props.doAction() may result in your ancestor re-rendering and providing you with new props. If setState is called directly with an object literal referencing `this.props`, it will use the *old* version of props, not the new value. Using a function solves for this case:
```
this.props.doAction();
this.setState((state, props) => ({ number: state.number * props.multiplier }));
```Changed paths5 files
First-parent comparisonsrc/core/ReactCompositeComponent.js ModifiedM src/core/ReactUpdateQueue.js ModifiedA src/core/__tests__/ReactCompositeComponentNestedState-test.js AddedM src/core/__tests__/ReactCompositeComponentState-test.js ModifiedM src/modern/class/ReactComponent.js ModifiedPatch
Files changed
Rendering syntax-highlighted changes…