Common gotchas in React

August 2018

While learning React, I encountered a few “gotchas”, a word that I despise but use anyway because it helps communicate a point. These were a few interesting cases that required a Google search or two:

  • The biggest one for me was that setState is asynchronous. So if you call setState and then immediately afterwards check against this.state, it probably won’t be updated yet. The solution? You should use a callback function as the second parameter in setState, which will fire after the state update is complete.
    enable() {
      this.setState({ enabled: true }, () => {
        console.log(this.state.enabled) // true
      })
    }
    
  • Along the same lines, if you’re trying to calculate a new state based on a property in the old state, you should pass in the old state as an argument. This is because this.setState is asynchronous.
  • Component names have to be capitalized, because in JSX, any component that starts with a lowercase letter is assumed to be a built-in HTML or SVG element.
  • Every element must be closed, even the ones that you might be used to leaving open (for instance, <br> should be changed to <br />).
  • You must use a different commenting style inside JSX. Due to the “less than” (<) sign, the compiler thinks that HTML comments are a malformed component. So you should open curly brackets and use a JavaScript comment instead:
    // This doesn't work:
    const ExampleA = () =>
      <div>
        <!-- This is a comment -->
      </div>
    
    // But this does:
    const ExampleB = () =>
      <div>
        {/* This is a comment */}
      </div>