[Code Example] Using states in class component Reactjs

Total
0
Shares

A component can maintain internal state data with this.state. When a component’s state data changes, the rendered markup will be updated by re-invoking render(). Here we are using states in class component in reactjs

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
  }

  tick() {
    this.setState(state => ({
      seconds: state.seconds + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
      <div>
        Seconds: {this.state.seconds}
      </div>
    );
  }
}

root.render(<Timer />);

Source: Reactjs Docs

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like