Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use shouldComponentUpdate in a PureComponent

I know the functionality for shouldComponentUpdate as well as PureComponent. But I'm wondering if I can use the two together?

Say I have lots of props which I want to let the shallow compare handle within PureComponent. Except 1 prop, which needs to be compared a bit cleverly. So is it possible to use shouldComponentUpdate for it? Which result would React consider?

In other words, would React call PureComponent's shallow compare and then call my shouldComponentUpdate? or my shouldComponentUpdate would override the original one?

It would be nice if its two-layered, if PureComponent returns false, the control comes into my shouldComponentUpdate where I have another opportunity to return false.

like image 431
Salman Avatar asked Jun 13 '17 07:06

Salman


1 Answers

You would first in the development environment get a warning as the React source code check to see if the method is defined or not when dealing with a PureComponent:

if (
  isPureComponent(Component) &&
  typeof inst.shouldComponentUpdate !== 'undefined'
) {
  warning(
    false,
    '%s has a method called shouldComponentUpdate(). ' +
      'shouldComponentUpdate should not be used when extending React.PureComponent. ' +
      'Please extend React.Component if shouldComponentUpdate is used.',
    this.getName() || 'A pure component',
  );
}

Then, when rendering, if this method is defined, it'll actually skip and not even check if the component is a PureComponent and use your own implementation.

if (inst.shouldComponentUpdate) {
  if (__DEV__) {
    shouldUpdate = measureLifeCyclePerf(
      () => inst.shouldComponentUpdate(nextProps, nextState, nextContext),
      this._debugID,
      'shouldComponentUpdate',
    );
  } else {
    shouldUpdate = inst.shouldComponentUpdate(
      nextProps,
      nextState,
      nextContext,
    );
  }
} else {
  if (this._compositeType === ReactCompositeComponentTypes.PureClass) {
    shouldUpdate =
      !shallowEqual(prevProps, nextProps) ||
      !shallowEqual(inst.state, nextState);
  }
}

So by implementing your own shouldComponentUpdate on a PureComponent, you would lose the shallow comparison.

like image 200
HiDeo Avatar answered Oct 05 '22 22:10

HiDeo