Table of Contents

React Class Component - Local State

About

state management in class component

In React, mutable state is typically kept in the state property of components, and only updated with setState().

Rules

Wrong, this code may fail to update the counter.
this.setState({
  counter: this.state.counter + this.props.increment,
});
Correct. Passes a function rather than an object.
this.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});
// or with the arrow function notation
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

Process

Shared State

When a state is shared between components, the common technique is lifting up the state to their closest common ancestor. See React Class Component - Shared State (Lifting state up)

Example

class Clock extends React.Component {

  //  Since Clock needs to display the current time, the constructor initializes this.state
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  // When the Clock output is inserted in the DOM, React calls the componentDidMount() lifecycle hook. 
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  //  Called if the Clock component is ever removed from the DOM, so the timer is stopped.
  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    // Thanks to the setState() call, React knows the state has changed, and calls render() method again.
    this.setState({
      date: new Date()
    });
  }

  // React learns what should be displayed on the screen. 
  // React then updates the DOM to match the Clock's render output.
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->
</div>