Call setState with null to Avoid Triggering an Update in React 16

Nik Graf
InstructorNik Graf

Share this video with your friends

Send Tweet

Sometimes it’s desired to decide within an updater function if an update to re-render should be triggered. Calling .setState with null no longer triggers an update in React 16. This means we can decided if the state gets updated within our .setState method itself!

In this lesson we'll explore how this works by refactoring a city map app that updates even if you choose the same map twice.

Hozefa
Hozefa
~ 4 years ago

Why is this better than shouldcomponentupdate? Doing logic inside setState kinda pollutes the paradigm of setState. Also at least in this case its possible to have the same check outside.

mtKeller
mtKeller
~ 4 years ago

Why is this better than shouldcomponentupdate? Doing logic inside setState kinda pollutes the paradigm of setState. Also at least in this case its possible to have the same check outside.

Only my opinion, but it can help localizes your conditional logic into your functions as you need it and let's you maintain a separation of concerns. Versus over utilizing shouldComponentUpdate as a catch all conditional function. Just like the rest of JS it just gives you a little more rope to play with.

Shiva
Shiva
~ 4 years ago

Versus over utilizing shouldComponentUpdate as a catch all conditional function

@mtKeller: In the above case, city component keeps re-rendering whenever render method is called on App. App could be a big component and could depend on lot of states and props to render. If any of those states/props update, it is going to call the render method, and <City /> component is going to do a fetch. So preventing a setState from happening doesn't solve the problem as some other state/prop update is going to re-fetch.

If City is a third party component that you have no control over, and you want it to not update if name prop changes, it is better to wrap it inside another component and you can call <WrappedCity name="Paris" /> instead. WrappedComponent will implement shouldComponentUpdate so that it only updates if city name changes. If <App /> wants to re-render for any reason, it won't forcefully update the City component.

Nik Graf
Nik Grafinstructor
~ 3 years ago

@Hozefa Just realized I never got back to this question and after thinking about it I believe I could have done a better example.

Let's say you have a button that increases a counter by one and you want to make sure it can't go beyond e.g. 5. I'm not aware of a nice setup where shouldComponentUpdate would help here. On the contrary you could check inside the setState function if the value is 5 and return null in such a case e.g.

setState((state) => {
  if (state.counter >= 5) return null;
  return { counter: state.counter + 1 }; 
});

I hope this helps!