React State
React components has a built-in state
object.
The state
object is where you store property values that belongs to the component.
When the state
object changes, the component re-renders.
Creating the state
Object
The state
object is initialized in the constructor:
Example:
Specify the state
object in the constructor method:
The state
object can contain as many properties as you like:
Example:
Specify all the properties your component need:
Using the state
Object
Refer to the state
object anywhere in the component by using the this.state.
propertyname syntax:
Example:
Refer to the state
object in the render()
method:
Changing the state
Object
When you call setState(), React merges the object you provide into the current state.
To change a value in the state object, use the this.setState()
method.
When a value in the state
object changes, the component will re-render, meaning that the output will change according to the new value(s).
Example:
Add a button with an onClick
event that will change the color property:
Always use the setState() method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods).
The Data Flows Down
Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn’t care whether it is defined as a function or a class.
This is why state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it.
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.
In React apps, whether a component is stateful or stateless is considered an implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa.