Keep Moving Forward | X-Team Magazine

Optimize Your React Re-Renders with Functional setState()

Written by Kelvin De Moya | Aug 12, 2021 4:00:00 AM

React programmers usually update state by passing an object that describes the changes we'd like to make. React then assigns the values and triggers an update. But what if I told you that you can pass a function to setState()? That's right, there's a functional side to React.

Here's how it works: You pass a function to setState() that takes state and props as parameters and returns your desired state, which React will then use for the update. We go from this:

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

To this:

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

this.setState(addAnotherPizza);

This means you can decouple the state update logic from your components and export it to a new file to make it reusable and declarative. Sweet!

How Does That Optimize Re-Renders?

Well, you can now prevent state updates and re-renders straight from setState(). You just need to have your function return null. For example, there is a maximum number of pizzas I can eat before I pass out. We don't want to continue updating and re-rendering after that point. There are many ways you can prevent that in React, but here's how you do it with 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
  return {
    pizza: state.pizza + 1,
  }
}

this.setState(addAnotherPizza);

This was a simple example of the implications and power of going functional with setState(). If you want to dive deeper, have a look at this nicely detailed article. Otherwise, happy coding!