Can I use shouldComponentUpdate in PureComponent

I know the functionality for shouldComponentUpdateas well PureComponent. But I wonder if I can use them together?

Let's say I have a lot of details that I want to allow a small comparison handle in PureComponent. Except for 1 prop, which needs to be compared a little cleverly. So is it possible to use shouldComponentUpdatefor this? What result will React consider?

In other words, would a React call be a PureComponentshallow comparison and then call my shouldComponentUpdate? or mine shouldComponentUpdatewill override the original?

It would be nice if its two-layer, if it PureComponentreturns false, the control enters mine shouldComponentUpdate, where I have one more possibility return false.

+4
source share
2 answers

First, you will receive a warning in the development environment as a React source code to check if a method is defined when working 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 will actually skip  and not even check if the component is PureComponentand 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, if you implement your own shouldComponentUpdateon PureComponent, you will lose the shallow comparison.

+5
source

According to doc: https://facebook.imtqy.com/react/docs/react-component.html#shouldcomponentupdate

, , React.PureComponent, shouldComponentUpdate() prop state. , , this.props nextProps this.state nextState false, React, .

, shouldComponentUpdate, , , PureComponent

0

Source: https://habr.com/ru/post/1679111/


All Articles