React 16: Prevent Unnecessary Re-Renders With Functional setState()

You may or may not know this already, but you can follow a functional approach when using React's setState(), We usually update our state just passing an object describing the changes we would like to make and let React assign those values and trigger an update, but...

But... how?

You can pass a function to setState() that takes state and props as params and returns your desired state, which React will use for the update.

You can go from:

// Increase the number of pizzas I need to eat.
this.setState({ pizzas: this.state.pizzas + 1 });

That means you could even decouple your state update logic from your components and export it from a new file to make it reusable and declarative. Sweet!

What about the re-renders?

Right, I almost forgot about the main point of this article. You can now prevent state updates and re-renders right from setState(). You just need to have your function return null.

So for example, there has to be a maximum number of pizzas I can eat before I pass out, and we do not want to continue updating and re-rendering after that point. There are many ways we could prevent that in React, but here is a new way using functional setState():

This was a really simple example of the implications and the power of going functional with setState(). If you are interested in going deeper, you can read this nicely detailed article and/or follow the master Jedi himself on Twitter, Mr. Dan Abramov.