React State

State is similar to props, but it is private and fully controlled by the component.

class constructor

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name “constructor” in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.

Class components should always call the base constructor with props.

  1. constructor(props) {
  2. super(props);
  3. this.state = {date: new Date()};
  4. }

Adding Lifecycle Methods to a Class

  • componentDidMount(): The componentDidMount() method runs after the component output has been rendered to the DOM.
  • componentDidUnmount(): clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React. ```javascript componentDidMount() { this.timerID = setInterval(
    1. () => this.tick(),
    2. 1000
    ); }

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

tick() { this.setState({ date: new Date() }); }

  1. <a name="fRi5m"></a>
  2. ## Do Not Modify State Directly
  3. ```javascript
  4. // Wrong
  5. this.state.comment = 'Hello';
  6. // Correct
  7. this.setState({comment: 'Hello'});

State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

  1. // Wrong
  2. this.setState({
  3. counter: this.state.counter + this.props.increment,
  4. });
  5. // Correct
  6. this.setState((state, props) => ({
  7. counter: state.counter + props.increment
  8. }));

The Data Flows Down

Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn’t care whether it is defined as a function or a class.

This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.

  1. function App() {
  2. return (
  3. <div>
  4. <Clock />
  5. <Clock />
  6. <Clock />
  7. </div>
  8. );
  9. }
  10. ReactDOM.render(
  11. <App />,
  12. document.getElementById('root')
  13. );