TIL React - SetState
POSTED ON:
TAGS: react
props
get passed to the component (similar to function parameters).
state
is managed within the component (similar to variables declared within a function).
Calls to setState
are asynchronous - don’t rely on this.state
to reflect the new value immediately after calling setState
. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).
//won't work
incrementCount() {
this.setState({count: this.state.count + 1});
}
//will work
incrementCount() {
this.setState((state) => {
// Important: read `state` instead of `this.state` when updating.
return {count: state.count + 1}
});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
}
Related TILs
Tagged: react