Vatsal Harde
Vatsal Harde

Reputation: 1548

How can i use setstate without Re-render of component in React js?

constructor(props, context) {
super(props);
this.state = {
ShowVoucher: false
 }

I want to change state of showVoucher. without Re-Render of component. i have tried like this

componentDidUpdate(prevState) {
if(prevState.showVoucher!= this.state.showVoucher){
  this.setState({ ShowVoucher: false})
}
  }

But my code stucks in infinite loop. How can i solve it? Any other solutions are welcome.

Upvotes: 0

Views: 4312

Answers (2)

ProblemsEverywhere
ProblemsEverywhere

Reputation: 547

Maybe what you are looking for is shouldComponentUpdate
https://reactjs.org/docs/react-component.html#shouldcomponentupdate

shouldComponentUpdate(nextProps, nextState) {
  if(this.state.showVoucher!==nextState.showVoucher){
   this.setState({ ShowVoucher: false})
   return false;
  } else return true;
}

Upvotes: -1

Jayce444
Jayce444

Reputation: 9063

If you want to store a value but not have the component re-render when that value changes, it shouldn't be in the state. It should be just an instance variable, e.g.

constructor(props, context) {
    this.ShowVoucher = false;
}

and then

this.ShowVoucher = true;

Do not put things in state then try to stop their changing from causing a re-render. That's an anti-pattern.

Upvotes: 2

Related Questions