How to learn react logo

These tutorials will give you a deeper understanding of React.js. Learn with examples from the Javascript UI library, covering the basics and the advanced.

Browse by tag:

Initializing state in componentDidMount vs in the constructor

State

States in React are objects that are used to store data and affect how the component renders. They're managed completely within the component and can be changed over time (by things like user actions and API requests).

As we know, components can have an initial state set. For example:

import React, { Component } from 'react';

class Accessories extends Component {
  constructor() {
    super()

    this.state = {
      jewelry: ['bracelet', 'earrings']
    }
  }
}

...

An alternative way to set state is using setState(). This function tells React that the component (and its children) need to be re-rendered with the updated state. componentDidMount() is a great place to call this function, as it's invoked immediately after a component is mounted. If you call setState() in componentDidMount, it will trigger an extra rendering, but it will happen before the browser updates the screen thus render() will be called twice. Here's an example:

import React, { Component } from 'react';

class Accessories extends Component {
  constructor() {
    super()

    this.state = {
      jewelry: []
    }
  }
}

componentDidMount() {
  this.setState({
    jewelry: 'bracelet', 'earrings'
  })
}

...

How To Learn React is designed and developed by me, Blake Fletcher. It is a project intended to share the things I learn while working with the UI library. As I build things, complete tutorials, read blog posts, and watch videos, I'll add to the site. I hope to eventually bring on other contributors. If interested, send me an email at blkfltchr@gmail.com.