Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is state in React?

I know that state allows us to create components that are dynamic and interactive but I want to deep in state.

Can someone help me to understand state in React using a real life example?

like image 765
Jon Avatar asked Jan 26 '19 15:01

Jon


3 Answers

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

like image 136
Isaac Avatar answered Oct 05 '22 21:10

Isaac


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

like image 22
meine Avatar answered Oct 05 '22 20:10

meine


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.

like image 40
Sahil Raj Thapa Avatar answered Oct 05 '22 20:10

Sahil Raj Thapa