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.
Here we have an application rendering a map of the selected city. You can switch the city by clicking on one of these buttons. One you do that, a new map is loaded and rendered after loading is complete. The application initializes the city name, a state, and a constructor.
The city name is passed to the city component, which is actually rendering the map. In addition, we have two buttons allowing us to change the selected city. Unfortunately, the city component doesn't check for changes, and loads the map every time an update is triggered.
There are multiple ways to solve this. For once, improving the city component, but this might be out of your control. An alternative is to prevent the new update. To do so, we can leverage a new feature of React 16.
We improve our select city method to check the new value is the same as the existing one. When they are the same, we simply return null for set state. This prevents an update being triggered.
When clicking on Paris, the city map loads, but when clicking on it a second or even a third time, it won't anymore, since the update was prevented. When clicking on Vienna, it will still switch and load the map.