this.state vs state in React

J Seabolt picture J Seabolt · Jun 30, 2018 · Viewed 13.8k times · Source

I'm working in a new codebase. Normally, I would set up state like this in a React component:

class App extends React.Component {
    constructor() {
        super();
        this.state={
            foo: 'bar'
        }
     }
    ....

In this new codebase, I'm seeing a lot of this:

class App extends React.Component {
    state={
        foo: 'bar'
     }
    ....

Is there an advantage to doing it this way? They seem to only do it when state doesn't need to be altered. I always thought of state as being something React handled. Is this an ok thing to do?

Answer

Tholle picture Tholle · Jun 30, 2018

The end result of both approaches is the same. Both approaches are just setting the initial state of the component. It's worth noting that class properties are a stage 3 proposal, so all development environments may not be able to use them.

I personally like to use the class field variant if nothing else is done in the constructor, as it is less code to write, and you have no super call to worry about.

Example

class Component1 extends React.Component {
  state = { value: this.props.initialValue };

  render() {
    return <div> {this.state.value} </div>
  }
}

class Component2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: props.initialValue };
  }

  render() {
    return <div> {this.state.value} </div>
  }
}

function App() {
  return (
    <div>
      <Component1 initialValue={1} />
      <Component2 initialValue={2} />
    </div>
  );
}