React Component State
Components can have state, which is a private part of a component's data used to manage dynamic data.
State only applies to class components, or can be used in function components when using React Hooks.
React views components as state machines. Through interaction with the user, different states are achieved, and then the UI is rendered to keep the user interface and data consistent.
In React, you only need to update a component's state and then re-render the user interface based on the new state (do not manipulate the DOM).
The following example creates an ES6 class extending React.Component that uses this.state in the render() method to modify the current time.
Add a class constructor to initialize the state this.state; class components should always call the base constructor with props.
State Management in Class Components
Create a stateful class component:
Counter.js file
import
React
,
{
Component
}
from
'react'
;
class
Counter
extends
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
count
:
0
}
;
}
increment
=
(
)
=>
{
this
.
setState
(
{
count
:
this
.
state
.
count
1
}
)
;
}
render
(
)
{
return
(
<
div
<
p
Count:
{
this
.
state
.
count
}
p
<
button onClick
=
{
this
.
increment
}
Increment
button
div
)
;
}
}
export
default
Counter
;
Render this component in src/index.js:
Example
import
React from
'react'
;
import
ReactDOM from
'react-dom'
;
import
'./index.css'
;
import
Counter from
'./Counter'
;
const
root
=
ReactDOM.
createRoot
(
document.
getElementById
(
"root"
)
)
;
// Render the Counter component
root.
render
(
<
Counter
/>
);
State Management in Function Components (Using Hooks)
Using React Hooks, you can use state in function components. The most commonly used Hook is useState.
Create a stateful function component:
Counter.js file
import
React
,
{
useState
}
from
'react'
;
function
Counter
(
)
{
const
[
count
,
setCount
]
=
useState
(
0
)
;
return
(
<
div
<
p
Count:
{
count
}
p
<
button onClick
=
{
(
)
=>
setCount
(
count
1
)
}
Increment
button
div
)
;
}
export
default
Counter
;
Render this component in src/index.js:
Example
import
React from
'react'
;
import
ReactDOM from
'react-dom'
;
import
'./index.css'
;
import
Counter from
'./Counter'
;
const
root
=
ReactDOM.
createRoot
(
document.
getElementById
(
"root"
)
)
;
// Render the Counter component
root.
render
(
<
Counter
/>
);
Example
Create a time-point example to understand component state:
React example
class
Clock
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
date
:
new
Date
(
)
}
;
}
render
(
)
{
return
(
<
div
<
h1
Hello
,
world!
h1
<
h2
The time is now
{
this
.
state
.
date
.
toLocaleTimeString
(
)
}
.
h2
div
)
;
}
}
const
root
=
ReactDOM
.
createRoot
(
document
.
getElementById
(
"
root
"
)
)
;
root
.
render
(
<
Clock
/>
);
Try it »
Next, we will make Clock set up its own timer and update every second.
Adding Lifecycle Methods to a Class
In applications with many components, it is important to release the resources occupied by a component when it is destroyed.
Whenever the Clock component is first loaded into the DOM, we want to generate a timer, which in React is calledmounting。
Similarly, whenever this DOM generated by Clock is removed, we want to clear the timer, which in React is calledUninstall。
We can declare special methods on a component class to run some code when the component mounts or unmounts:
React example
class
Clock
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
date
:
new
Date
(
)
}
;
}
componentDidMount
(
)
{
this
.
timerID
=
setInterval
(
(
)
=>
this
.
tick
(
)
,
1000
)
;
}
componentWillUnmount
(
)
{
clearInterval
(
this
.
timerID
)
;
}
tick
(
)
{
this
.
setState
(
{
date
:
new
Date
(
)
}
)
;
}
render
(
)
{
return
(
<
div
<
h1
Hello
,
world!
h1
<
h2
The time is now
{
this
.
state
.
date
.
toLocaleTimeString
(
)
}
.
h2
div
)
;
}
}
const
root
=
ReactDOM
.
createRoot
(
document
.
getElementById
(
"
root
"
)
)
;
root
.
render
(
<
Clock
/>
);
Try it »
Example analysis:
The componentDidMount() and componentWillUnmount() methods are called lifecycle hooks.
The componentDidMount() hook is executed after the component output is inserted into the DOM, so we can set a timer in this hook.
this.timerID is the ID of the timer, and we can clear the timer in the componentWillUnmount() hook.
Code execution order:
-
When
is passed toReactDOM.render(), React callsClockthe component's constructor. SinceClockneeds to display the current time, it uses an object containing the current time to initializethis.state. We will update this state later. -
React then calls
Clockthe component'srender()the method. This is how React learns what should be displayed on the screen, and then React updates the DOM to matchClock's rendered output. -
When
ClockWhen the output is inserted into the DOM, React callscomponentDidMount()the lifecycle hook. Inside it,Clockthe component asks the browser to set a timer that callstick()。 -
once every second. The browser calls
tick()every second. Inside it,Clockthe component callssetState()to schedule a UI update by using an object containing the current time. By callingsetState(), React knows that the state has changed and callsrender()again to determine what should be displayed on the screen. This time,render()the in thethis.state.datemethod will be different, so the rendered output will contain the updated time and the DOM will be updated accordingly. -
Once the
Clockcomponent is removed from the DOM, React callscomponentWillUnmount()this hook function, and the timer is cleared.
Data Flows Top-Down
Neither a parent nor a child component needs to know whether a component is stateful or stateless, and they should not care whether a component is defined as a function or a class.
This is why state is often called local or encapsulated. It is inaccessible to any component other than the one that owns and sets it.
In the following example, the FormattedDate component receives the date value in its props and does not know whether it comes from Clock's state, from Clock's props, or is manually entered:
React example
function
FormattedDate
(
props
)
{
return
<
h2
The time is now
{
props
.
date
.
toLocaleTimeString
(
)
}
.
h2
;
}
class
Clock
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
date
:
new
Date
(
)
}
;
}
componentDidMount
(
)
{
this
.
timerID
=
setInterval
(
(
)
=>
this
.
tick
(
)
,
1000
)
;
}
componentWillUnmount
(
)
{
clearInterval
(
this
.
timerID
)
;
}
tick
(
)
{
this
.
setState
(
{
date
:
new
Date
(
)
}
)
;
}
render
(
)
{
return
(
<
div
<
h1
Hello
,
world!
h1
< FormattedDate date = { this.
state
.
date
}
/>
div
)
;
}
}
const
root
=
ReactDOM
.
createRoot
(
document
.
getElementById
(
"
root
"
)
)
;
root
.
render
(
< Clock /> );
Try it »
This is commonly referred to as top-down or unidirectional data flow. Any state is always owned by a specific component, and any data or UI derived from that state can only affect components below it 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 connects at an arbitrary point but also flows downward.
To show that all components are truly isolated, we can create an App component that renders three Clocks:
React example
function
FormattedDate
(
props
)
{
return
<
h2
The time is now
{
props
.
date
.
toLocaleTimeString
(
)
}
.
h2
;
}
class
Clock
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
date
:
new
Date
(
)
}
;
}
componentDidMount
(
)
{
this
.
timerID
=
setInterval
(
(
)
=>
this
.
tick
(
)
,
1000
)
;
}
componentWillUnmount
(
)
{
clearInterval
(
this
.
timerID
)
;
}
tick
(
)
{
this
.
setState
(
{
date
:
new
Date
(
)
}
)
;
}
render
(
)
{
return
(
< div < h1 Hello , world!
h1
< FormattedDate date = { this.
state
.
date
}
/>
div
)
;
}
}
function
App
(
)
{
return
(
< div < Clock/> <
Clock
/> <
Clock
/>
div
)
;
}
const
root
=
ReactDOM
.
createRoot
(
document
.
getElementById
(
"
root
"
)
)
;
root
.
render
(
< App /> );
Try it »
In the above example, each Clock component sets up its own timer and updates independently.
In React applications, whether a component is stateful or stateless is considered an implementation detail that may change over time.
We can use stateless components inside stateful components, and stateful components inside stateless components.