I have been reading the React docs and came across shouldComponentUpdate()
. My understanding is that everytime setState()
is called, a re-render of that component will be updated.
My question is that If the value to be updated is the SAME as the current state value, would this trigger a re-render event? or I would have to manually checks for the current value and value to be updated in shouldComponentUpdate()
The official React documentation states:
https://reactjs.org/docs/react-component.html#shouldcomponentupdate
This means that by default,
render()
will be executed if any of a component'sstate
orprops
values changes.You can override this default behavior using shouldComponentUpdate(). Here's an example that only updates if a state value changes.
Note: this example completely ignores
props
. So, any changes toprops
will not triggerrender()
.Adding more to @Jyothi's answer regarding implementing
shouldComponentUpdate()
to skip unnecessary re-renders, inReact 15.3
they introduced a new conceptPureComponent
. From reactjs docsThis allows to skip unnecessary calls of
render
in class components by just implementingPureComponent
instead of the usualComponent
. There are a few caveats withPureComponent
though, from the docs aboutReact.PureComponent
’sshouldComponentUpdate()
:Usage of
PureComponent
can in some cases improve performance of your app. Moreover, it enforces you to keepstate
andprops
objects as simple as possible or even better, immutable, which might help simplify the app structure and make it cleaner.I dont know if I understood your question correctly but react only re renders when there is difference between virtual dom and real dom.
And as Jyothi mentioned in his answer that render method will be called irrespective of the value passed in the set state function but rerendering will depend on what this render method returns.