setState
void setState( function|object nextState, [function callback] )
Performs a shallow merge of nextState into current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks.
The first argument can be an object (containing zero or more keys to update) or a function (of state and props) that returns an object containing keys to update.
Here is the simple object usage:
setState({mykey: 'my new value'});
It's also possible to pass a function with the signature function(state, props). This can be useful in some cases when you want to enqueue an atomic update that consults the previous value of state+props before setting any values. For instance, suppose we wanted to increment a value in state:
setState(function(previousState, currentProps) {
return {myInteger: previousState.myInteger + 1};
});
The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered.
Notes:
NEVER mutate
this.statedirectly, as callingsetState()afterwards may replace the mutation you made. Treatthis.stateas if it were immutable.
setState()does not immediately mutatethis.statebut creates a pending state transition. Accessingthis.stateafter calling this method can potentially return the existing value.There is no guarantee of synchronous operation of calls to
setStateand calls may be batched for performance gains.
setState()will always trigger a re-render unless conditional rendering logic is implemented inshouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented inshouldComponentUpdate(), callingsetState()only when the new state differs from the previous state will avoid unnecessary re-renders.
Please login to continue.