Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs: Stop rerendering on a particular state change with shouldComponentUpdate()

Tags:

reactjs

I have multiple setState in my component onload. My page is re-rendering on click of dropdown values, because on-click I'm storing those values via setState.

Here to stop re-rendering on click, I'm using the below code.

shouldComponentUpdate() {
    return false
}

Now because of the above function, My values are not storing in state on page load. Is there anything I need to do extra ?

like image 383
David Avatar asked Dec 18 '22 06:12

David


1 Answers

You states don't show a change in your component, because it doesn't rereder at all, since you have returned false from the shouldComponentUpdate method.

If you want to restrict rendering on particular state change then just check for that state and return false else return true like

shouldComponentUpdate(nextProps, nextState) {
     if(this.state.dropdownVal != nextState.dropdownval) {
          return false
     }
     return true
}

However its not such a bad thing to rerender because React rendering process is very efficient and you would want to show the updated state in the DOM more often then not.

like image 184
Shubham Khatri Avatar answered Dec 31 '22 02:12

Shubham Khatri