Home > Net >  React Native: shouldComponentUpdate() not preventing render() from being called
React Native: shouldComponentUpdate() not preventing render() from being called

Time:05-05

I have a React Native component where I want to prevent the render() method from being called.

class A extends Component {
  shouldComponentUpdate() {
    return false;
  }
  render() {
    return(...)
  }
}

Returning false in shouldComponentUpdate should prevent render() from being called, but it doesn't. Is there something I'm doing wrong?

CodePudding user response:

Indeed, it prevents a rerender but not the initial rendering. This is documented here.

Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.

and

shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

Hence, if you return false, then you only prevent a rerendering on state changes.

CodePudding user response:

you can try use hooks useMemo or useCallback https://reactjs.org/docs/hooks-reference.html to choose what you want to update

  • Related