Melissa94
Melissa94

Reputation: 423

compare different state array in getDerivedStateFromProps

How to compare states in array? I can't use !== or use .length

static getDerivedStateFromProps(props, state) {
    if(props.languages !== statelanguages)) {
      return {
        languages: props.languages
      }
    }
    return null
  }

I can use isEqual from lodash but won't that be overkill?

Upvotes: 1

Views: 559

Answers (1)

Mrchief
Mrchief

Reputation: 76218

That depends on how thorough your check should be. If you want to be absolutely certain that 2 arrays completely match - which means all of their elements match - then simple length or reference check will not suffice. You will need lodash.isEqual or something similar.

Note that lodash.isEqual will be very quick if props.languages and statelanguages are "reference" equal, which means if props.languages === statelanguages evaluates to true, it'll return true right away. If not, then it proceeds to check for length checks and deep equality checks - the last one can get costly if your array sizes are big.

Upvotes: 1

Related Questions