What is state in React?
import React from 'react';
class App extends React.Component {
state = {
count: 0
};
render() {
return (
<div>
<h1>Hello world</h1>
<h2>Count: {this.state.count}</h2>
<button
onClick={() => this.setState(state => ({ count: state.count + 1 }))}
>
+
</button>
<button
onClick={() => this.setState(state => ({ count: state.count - 1 }))}
>
-
</button>
</div>
);
}
}
export default App;
In the above code, it has a state
object with property/state
: count.
State can simply be understand as a value at that point of time of the particular component/app. In the above example, when the app is first running, the app is with state count === 0
As we can see there are two buttons +
and -
that update the value using this.setState
, it simply update the "state" of count for the app, and the app will re-render, whenever the state change
For example:
import React, { Component } from "react";
import ReactDOM from "react-dom";
class App extends Component {
state = {
show: false,
}
showTextToggle = () => {
this.setState({ show: !this.state.show });
}
render() {
const { show } = this.state;
return (
<div>
<h3>Some title</h3>
{show ? <div>Description</div> : undefined}
<button onClick={this.showTextToggle}>Read more</button>
</div>
)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
P.S. CodeSandBox
State in real life example:
Before someone upvoted your question, you can imagine your question or think it as question component had vote state = 0
and after that it became 1 and so on. So interactivity with the application changed something in the application. That changed something/ value can be called state.
State in application/ component can change due to interactivity(event) or during time.
As time you can imagine this Post or Post Component
before 30 minutes/ some time ago had no answer i.e answer state = 0
. And now it has some (3) answers. So answer state = 0
changed to answer state = 3
.
State is just a value that a component/app is in at particular time.
Just imagine the specific point of time when you posted this question and now see the changes in this post. This changes can be thought as change in the state of the component/ app.