State
- When you call
setState()
, React merges the object you provide into the current state. - A component may choose to pass its state down as props to its child components.
- This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.
CSS Tricks — React “state” from the ground up
state
is a JS object that allows you keep track of a component’s data.- Changes can be based on user response, new messages from server-side, network response, or anything.
- Component state is expected to be private to the component and controlled by the same component.
- To make changes to a component’s state, you have to make them inside the component.
- The constructor is the right place to initialize state.
- State is accessed in the
render()
method. - State is only updated using the
setState()
method. Never assign tothis.state
directly. - State can be passed as props from parent to child components.
CSS Tricks — Understanding React “setState”
- Treat
setState()
asynchronously. - Pass an object to
setState()
when updating state once. - Pass a function to
setState()
when updating state multiple times. - Don’t depend on
this.state
immediately after callingsetState()
. Use an updater function instead.
Inline updater function:
handleIncrement = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
this.setState((prevState) => ({ count: prevState.count + 1 }));
this.setState((prevState) => ({ count: prevState.count + 1 }));
}
External updater function:
changeCount = () => {
this.setState((prevState) => {
return { count: prevState.count - 1}
});
};
handleIncrement = () => {
this.changeCount();
this.changeCount();
this.changeCount();
};
Uber React Guide — Props vs State
- If an attribute of a
component
may change at some time, it should be part ofstate
. Otherwise use aprop
. - State is optional. Since state increases complexity and reduces predictability, a
component
without state is preferable.
Usage | props | state |
---|---|---|
Can get initial value from parent Component? | Yes | Yes |
Can be changed by parent Component? | Yes | No |
Can set default values inside Component?* | Yes | Yes |
Can change inside Component? | No | Yes |
Can set initial value for child Components? | Yes | Yes |
Can change in child Components? | Yes | No |