Newer Post

6 Simple Examples Which Will Make You Love Observables (rxjs 5)

Older Post

Getting Familiar With Gulp for Workflow Automation

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...

What if I told you... You can pass a function to setState?

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 });  

to

// Increase the number of pizzas I need to eat.
function addAnotherPizza(state, props) {  
  return {
    pizza: state.pizza + 1,
  }
}

this.setState(addAnotherPizza);  

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():

const MAX_PIZZAS = 20;

function addAnotherPizza(state, props) {  
  // Stop updates and re-renders if I've had enough pizzas.
  if (state.pizza === MAX_PIZZAS) {
    return null;
  }

  // If not, keep the pizzas coming! :D
  return {
    pizza: state.pizza + 1,
  }
}

this.setState(addAnotherPizza);  

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.

That is all, for now, folks, may the X be with you, always!

We'll help you unleash.

Join the 20,000 developers who subscribe to our newsletter.

Scale your
Development team

We help you execute projects by providing trusted developers who can join your team and immediately start delivering high-quality code.

Hire Developers
code, react, functional programming