Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent React Native from re-rendering to many times

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)}
    />
  );
}
like image 553
Jerry seigle Avatar asked Jan 21 '26 16:01

Jerry seigle


1 Answers

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
  }
}
like image 156
needsleep Avatar answered Jan 24 '26 12:01

needsleep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!