[React MAIN CONCEPTS] 5. State and Lifecycle
5. State and Lifecycle
This page introduces the concept of state and lifecycle in a React component. You can find a detailed component API reference here - https://reactjs.org/docs/react-component.html.
Consider the ticking clock example from one of the previous sections. In Rendering Elements, we have only learned one way to update the UI. We call ReactDOM.render()
to change the rendered output:
1 | function tick() { |
Try it on CodePen - https://codepen.io/gaearon/pen/gwoJZk?editors=0010
In this section, we will learn how to make the Clock
component truly reusable and encapsulated. It will set up its own timer and update itself every second.
We can start by encapsulating how the clock looks:
1 | function Clock(props) { |
Try it on CodePen - https://codepen.io/gaearon/pen/dpdoYR?editors=0010
However, it misses a crucial requirement: the fact that the Clock
sets up a timer and updates the UI every second should be an implementation detail of the Clock
.
Ideally we want to write this once and have the Clock update itself:
1 | ReactDOM.render( |
To implement this, we need to add “state” to the Clock
component.
State is similar to props
, but it is private and fully controlled by the component.
Converting a Function to a Class
You can convert a function component like Clock
to a class in five steps:
-
Create an ES6 class - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes, with the same name, that extends
React.Component
. -
Add a single empty method to it called
render()
. -
Move the body of the function into the
render()
method. -
Replace
props
withthis.prop
s in therender()
body. -
Delete the remaining empty function declaration.
1 | class Clock extends React.Component { |
Try it on CodePen - https://codepen.io/gaearon/pen/zKRGpo?editors=0010
Clock
is now defined as a class rather than a function.
The render
method will be called each time an update happens, but as long as we render <Clock />
into the same DOM node, only a single instance of the Clock class will be used. This lets us use additional features such as local state and lifecycle methods.
Adding Local State to a Class
We will move the date from props
to state
in three steps:
-
- Replace
this.props.date
withthis.state.date
in therender()
method:
- Replace
1 | class Clock extends React.Component { |
-
- Add a class
constructor
that assigns the initialthis.state
:
- Add a class
1 | class Clock extends React.Component { |
Note how we pass props
to the base constructor
:
1 | constructor(props) { |
Class components should always call the base constructor with props
.
-
- Remove the
date
prop from the<Clock />
element:
- Remove the
1 | ReactDOM.render( |
We will later add the timer code back to the component itself.
The result looks like this:
1 | class Clock extends React.Component { |
Try it on CodePen - https://codepen.io/gaearon/pen/KgQpJd?editors=0010
Next, we’ll make the Clock
set up its own timer and update itself every second.
Adding Lifecycle Methods to a Class
In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.
We want to set up a timer whenever the Clock
is rendered to the DOM for the first time. This is called “mounting” in React.
We also want to clear that timer whenever the DOM produced by the Clock
is removed. This is called “unmounting” in React.
We can declare special methods on the component class to run some code when a component mounts and unmounts:
1 | class Clock extends React.Component { |
These methods are called “lifecycle methods”.
The componentDidMount()
method runs after the component output has been rendered to the DOM. This is a good place to set up a timer:
1 | componentDidMount() { |
Note how we save the timer ID right on this (this.timerID
).
While this.props
is set up by React itself and this.state has a special meaning, you are free to add additional fields to the class manually if you need to store something that doesn’t participate in the data flow (like a timer ID).
We will tear down the timer in the componentWillUnmount() lifecycle method:
1 | componentWillUnmount() { |
Finally, we will implement a method called tick()
that the Clock
component will run every second.
It will use this.setState()
to schedule updates to the component local state:
1 | class Clock extends React.Component { |
Try it on CodePen - https://codepen.io/gaearon/pen/amqdNA?editors=0010
Now the clock ticks every second.
Let’s quickly recap what’s going on and the order in which the methods are called:
-
- When
<Clock />
is passed toReactDOM.render()
, React calls theconstructor
of theClock
component. Since Clock needs to display the current time, it initializesthis.state
with an object including the current time. We will later update this state.
- When
-
- React then calls the
Clock
component’srender()
method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the Clock’s render output.
- React then calls the
-
- When the
Clock
output is inserted in the DOM, React calls thecomponentDidMount()
lifecycle method. Inside it, theClock
component asks the browser to set up a timer to call the component’stick()
method once a second.
- When the
-
- Every second the browser calls the
tick()
method. Inside it, theClock
component schedules a UI update by callingsetState()
with an object containing the current time. Thanks to thesetState()
call, React knows the state has changed, and calls therender()
method again to learn what should be on the screen. This time,this.state.date
in therender()
method will be different, and so the render output will include the updated time. React updates the DOM accordingly.
- Every second the browser calls the
-
- If the
Clock
component is ever removed from the DOM, React calls thecomponentWillUnmount()
lifecycle method so the timer is stopped.
- If the
Using State Correctly
There are three things you should know about setState()
.
Do Not Modify State Directly
For example, this will not re-render a component:
1 | // Wrong |
Instead, use setState():
1 | // Correct |
The only place where you can assign this.state
is the constructor.
State Updates May Be Asynchronous
React may batch multiple setState()
calls into a single update for performance.
Because this.props
and this.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
For example, this code may fail to update the counter:
1 | // Wrong |
To fix it, use a second form of setState()
that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
1 | // Correct |
We used an arrow function - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions above, but it also works with regular functions:
1 | // Correct |
State Updates are Merged
When you call setState()
, React merges the object you provide into the current state.
For example, your state may contain several independent variables:
1 | constructor(props) { |
Then you can update them independently with separate setState()
calls:
1 | componentDidMount() { |
The merging is shallow, so this.setState({comments})
leaves this.state.posts
intact, but completely replaces this.state.comments
.
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:
1 | <FormattedDate date={this.state.date} /> |
The FormattedDate
component would receive the date in its props
and wouldn’t know whether it came from the Clock’s state, from the Clock’s props, or was typed by hand:
1 | function FormattedDate(props) { |
[Try it on CodePen - https://codepen.io/gaearon/pen/zKRqNB?editors=0010[(https://codepen.io/gaearon/pen/zKRqNB?editors=0010)
]
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.
If you imagine a component tree as a waterfall of props, each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.
To show that all components are truly isolated, we can create an App component that renders three <Clock>
s:
1 | function App() { |
Try it on CodePen - https://codepen.io/gaearon/pen/vXdGmd?editors=0010
Each Clock sets up its own timer and updates independently.
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.
References
[1] State and Lifecycle – React - https://reactjs.org/docs/state-and-lifecycle.html
[2] React – A JavaScript library for building user interfaces - https://reactjs.org/
[3] React.Component – React - https://reactjs.org/docs/react-component.html
[4] Classes - JavaScript | MDN - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes