React components has a built-in
state object is where you store property values that belongs to the component.
state object changes, the component re-renders.
state object is initialized in the constructor:
state object in the constructor method:
state object can contain as many properties as you like:
Specify all the properties your component need:
Refer to the
state object anywhere in the component by using the
Refer to the
state object in the
When you call setState(), React merges the object you provide into the current state.
To change a value in the state object, use the
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).
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.