Using an object reference to set initial state in react

Hi Campers,

It’s been a while, hope you’ve all been keeping well.

Would this be ok?

const DEFAULT_STATE = {
  foo: foobar,
  bar: barfoo
}

class Tuna extends Component {
  constructor(props) {
    super(props)
    this.state = DEFAULT_STATE
  }
  ...
  reset = () => {
    this.setState(DEFAULT_STATE)
  }
  ...
}

or would this be any better (assuming there are no nested objects in DEFAULT_STATE)

const DEFAULT_STATE = {
  foo: foobar,
  bar: barfoo
}

class Tuna extends Component {
  constructor(props) {
    super(props)
    this.state = {...DEFAULT_STATE}
  }
  ...
  reset = () => {
    this.setState({...DEFAULT_STATE})
  }
  ...
}

or just plain old this

class Tuna extends Component {
  constructor(props) {
    super(props)
    this.state = {
      foo: foobar,
      bar: barfoo
    }
  }
  ...
  reset = () => {
    this.setState({
      foo: foobar,
      bar: barfoo
    })
  }
  ...
}

thank you.

My vote is for #1 :wink:

1 Like

1 probably is clearest? More personal choice here though.

As an aside:

import { useState } from. 'react';

const DEFAULT_STATE = { foo: foobar, bar: barfoo };

function Tuna() {
  const [foo, setFoo] = useState(DEFAULT_STATE.foo);
  const [bar, setBar] = useState(DEFAULT_STATE.bar);

  ...

  const reset = () => {
    setFoo(DEFAULT_STATE.foo);
    setBar(DEFAULT_STATE.bar);
  };

  ...
}

EDIT above code is react 16.7-alpha, not in release yet as they work bugs out, removes a lot of the need for classes and I’m :pray: :pray::pray: it gets approved

1 Like