Stan Luo
Stan Luo

Reputation: 3889

Can I access other state variables in state?

Is this considered to be an anti-pattern?

  state = {
    a: true,
    b: !this.state.a,
  }

If not, how could I do this, as this.state inside state is undefined?

Upvotes: 0

Views: 255

Answers (1)

Tyler Liu
Tyler Liu

Reputation: 20356

You shouldn't store both a and b in state if b could be derived from a.

Unneeded state is a bad practice - a code smell if you like to name it that way - that can make work with your component classes harder. Try to think about avoiding and refactoring your component classes to not create unneeded state. Always remember about the single source of truth principle - it can make your component classes simpler to write and maintain. Remember that every denormalised state field is a possible vector of easy bugs.

Ref: http://reactkungfu.com/2015/09/common-react-dot-js-mistakes-unneeded-state/

Upvotes: 1

Related Questions