kosker kosker - 3 months ago 8
React JSX Question

Is it safe to check object reference in componentWillReceiveProps?

I have a component connected to redux store and I have a code block like in this:

if (this.props.person !== nextProps.person) {
...
} else {
...
}

...

MyComponent.propTypes {
person: PropTypes.object.isRequired
}


Is it safe to check object reference in this way? Can I assume that in a reducer object reference will always change?

Answer

It is safe as long as your reducer is a pure function. To guarantee purity, those are the 3 most important things you should never do inside a reducer:

  • Mutate its arguments (use Object.assign or the object spread operator to avoid mutations on objects)
  • Perform side effects like API calls and routing transitions
  • Call non-pure functions, e.g. Date.now() or Math.random().

If your reducer satisfy all 3 conditions, any particular action dispatched that turned out to modify person property inside the state tree, will result in a new person object.

In that case, this.props.person and nextProps.person would be two different objects and that object reference check would be correct. However if a particular action dispatched didn't modify person property inside the state tree, this.props.person and nextProps.person would still be the same object