What Is a Pure Function? Why Do React Function Components Need to Be Pure?

February 14, 2023

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

With the emergence of React Hooks, Function Components in React have gradually become mainstream. One of the most common questions about Function Components is "Why do React function components need to be pure functions?" This article will answer this question in the first person.

What is a Pure Function?

A pure function is a function with two main characteristics. First, "the same input will always result in the same output." Second, it does not change anything outside of the function, in other words, it has no side effects.

For example, the function f(x) = 2x will always output 2 when the input is 1, and will output 4 when the input is 2. The output will always be the same no matter how many times it is called, which satisfies the first requirement of a pure function. However, if the function contains operations with randomness like Math.random(), the output may not be consistent, and thus it cannot be considered a pure function.

The absence of side effects and changes to anything outside of the function is shown in the following example. If the sayHi function changes the guest variable that was originally outside of the function, we cannot consider sayHi as a pure function.

let guest = 1;

function sayHi(message) {
  guest = guest + 1;
  return `${message} with ${guest} guests `;
}

Why Do React Function Components Need to Be Pure?

Function components in React must be pure because impure functions can cause unstable renderings and unexpected UI presentations, which are more likely to result in bugs.

If each input results in a different output, it can lead to an extremely unstable UI presentation. For example, in the code below, if we want to prepare chocolate pie ingredients based on the number of guests, and if a random number appears, the same number of guests may result in different ingredient quantities. This would be an undesirable bug if it were to appear on a recipe website.

function ChocolatePie({ guestNum }) {
	const milkNum = guestNum * Math.floor(Math.random() * 10)
	const chocolateNum = guestNum * 2

  return (
  <div> Add {milkNum} cups of milk and {chocolateNum} bars of chocolate </div>  );
}

// If these three components are actually rendered, the same guestNum will render different content
<ChocolatePie guestNum={3} />
<ChocolatePie guestNum={3} />
<ChocolatePie guestNum={3} />

If there are side effects, it can also cause unstable bugs. For example, in the code below from the React official example, changing guest outside of the Cup component will result in different content being rendered, even though the same Cup component is rendered. This kind of bug is also undesirable.

let guest = 0;

function Cup() {
  // Bad: changing a preexisting variable!
  guest = guest + 1;
  return <h2>Tea cup for guest #{guest}</h2>;
}

// If the following three Cup components are rendered, there will be different results
<Cup />
<Cup />
<Cup />

In conclusion, the presence of impure functions in function components can lead to instability and potential bugs, so when writing React code, we try to write pure functions as much as possible.

Bonus Questions: How to Detect Impure Functions in React?

In React, there are common functions besides function components, such as setState and context. When using them, we need to make sure they are pure functions. For example, if the props passed into the component as input, if the same props result in different outputs, it will lead to unstable bugs. Similarly, when we want to change a state, if we directly change the value instead of setState, it will cause side effects, which will also be more likely to result in bugs.

To avoid accidentally making these kinds of mistakes in React, we can easily use strict mode. When we turn on strict mode, React renders each component twice; any impure functions are likely to have different results in the two renders, which can help us detect where the problem is.

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee