Home > Blockchain >  How to prevent React Native from re-rendering to many times
How to prevent React Native from re-rendering to many times

Time:11-09

Currently my component is rendering 4 times. Looks like it is rendering for each prop. If I remove the props except network then it just render 1 time however I do need the other props. I am using a if statement inside the componentDidUpdate because I need to detect change however I am rendering 4 times and my network prop is the same

export class Camera extends Component {
  componentDidUpdate(prevProps, prevState){
    if (prevProps.network !== this.props.network){
      this.connect(this.props.network)
      console.log('rendering')
    }
  }
  
  connect=()=>{
    //
  }

  render() {
    return (
      <View>
        <Text>
          Hello World
        </Text>
      </View>
    )
  }
}

export default function (props) {
  return (
    <Camera
      navigation={props.navigation}
      route={props.route}
      network={React.useContext(NetworkContext)}
    />
  );
}

CodePudding user response:

By default, React will re-render every time props change at all. That guarantees React will never miss an update. If you want to render less often than that, implement shouldComponentUpdate and a custom validator:

shouldComponentUpdate(nextProps, nextState) {
  // Compare this.props / nextProps
  // Compare this.state / nextState
  // determine if update is needed
  return true;
}

CodePudding user response:

Since you're using React Class Component and not hooks maybe you can use the shouldComponentUpdate lifecycle method.

shouldComponentUpdate(nextProps, nextState)

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

Basically you can return false if you want your component to NOT render on some prop / state change

for example the following should only re render the component once the network prop has changed and not for any other prop change

shouldComponentUpdate(nextProps, nextState){
  if (nextProps.network !== this.props.network){
    return true
  } else {
    return false
  }
}
  • Related