React - State

As discussed at high level in my previous article, state and props are models in react which holds information. A state can be local to a component which can be shared with its subsequent children in the form of props. props is a pre-populated object in react which is passed to every component (class or functional) and holds data and methods shared by the caller component.

Lets look at state in detail.

React State

  • Its an object that includes any data for that component.
  • Any value/statement/expression can be rendered dynamically in the curly brackets {}.
  • We need to use this to refer to the current object for class components.

  •   import React from "react";
      import ReactDOM from "react-dom";

      class App extends React.Component {
        constructor() {
          super(); //always call super constructor as a first thing!
          this.state = {
            //create a state object, setup initial values (if applicable)
            name: "Hardik",
          };
        }
        render() {
          return (
            //React.Fragment
            <>
              //state value of name will be rendered dynamically
              <h2>Hi, my name is {this.state.name}!</h2>
            </>
          );
        }
      }

      ReactDOM.render(<App />, document.getElementById("container"));

  • Please note that we need to use curly brackets while referring to this.state.name above.
  • Curly brackets is a way by using which we can switch from JSX to JavaScript in the JSX code.
  • Without curly brackets, the JavaScript value will not be evaluated and JSX will treat it as a string.

Updating State

  • There will be scenarios where we need to change the state values of a component.
  • In react, using or changing state of the model directly wont reflect in view, as react is not aware of that change. The value will get updated but view change won’t happen.

  •   render() {
        this.state.name = "Rishabh"; //Try updating the value
        return (
          //React.Fragment
          <>
            //value of name will still be 'Hardik'
            <h2>Hi, my name is {this.state.name}!</h2> //this.state.name will be "Hardik"
          </>
        );
      }

  • Unlike angular, react doesn’t automatically runs its change detection algorithm to find out what has changed. We need to explicitly tell react what has changed
  • In order to tell react that state value has changes, we need to use a method called as setState.
  • setState method takes an object, and properties of the object will be either merged with what we have in the state object or those properties will be overwritten if they exist already. So we need to be very careful while updating the state.
  • setState works only after a component is entirely rendered, so calling setState in constructor will throw an error.


  •   render() {
        return (
          <>
            <h2>Hi, my name is {this.state.name}!</h2>
            //handle button onclick event, react needs attributes in camelCase!
            <button onClick={() => this.setState({ name: "Rishabh" })}>
              Change Name
            </button>
          </>
        );
      }

  • As states are local/private to a component, other components cannot access state of a component directly.
  • state can be passed down to immediate child component through props.
  • setState() call updates all children using the specific state

What happens when a state changes?

  • When setState is called, it suggests react that the state of the component is going to change.
  • React then schedules a call to render method of the component.
  • Its a asynchronous call and we don’t know when call will happen!
  • Render method will return new react element.
  • React does comparison of the old and new DOM, using its reconciliation algorithm.
  • Once the comparison is complete, then the specific html element(s) is mutated by react and react skips mutating other children or elements which are not modified or affected.






Comments

Popular Posts