The Power of Purity in React: A Guide to Pure Components and Error-Free Coding

Unlock the Secrets to Bug-Free React Apps: Why Are Pure Components and Strict Mode Essential?

The Power of Purity in React: A Guide to Pure Components and Error-Free Coding

Below is the excerpt from react.dev documentation:

"Some JavaScript functions are pure. Pure functions only perform a calculation and nothing more. By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behaviour as your codebase grows. To get these benefits, though, there are a few rules you must follow."

You will learn

  • What purity is and how it helps you avoid bugs

  • How to keep components pure by keeping changes out of the render phase

  • How to use Strict Mode to find mistakes in your components

What is purity?

In React, purity is characterized into:

It minds its own business: This means that the component should not mutate or depend on any object or variable during rendering. The component should only depend on the variables that are in the current scope of the component.

Same inputs, Same outputs: Pure functions are expected to return the same output if the inputs are the same every time. Let's take an example of a Card component that shows a user's data, so if we map this component through an array of users it should return the same card, it should not alter the jsx on every render, only the values should change.

How does it help you avoid bugs?

Let's take an example of an impure component and then we will convert it into a pure component.

Assume a parent component that has currentPrice variable and the child returns an h1 tag with the currentPrice from the parent and it adds 1 to it. So, if we make 3 copies of a child in the parent component then it will result in different values that are returned, this is an impure component! this will cause bugs that would become a nightmare to resolve.

To make it a pure component, let's follow the above characteristics, so instead of directly using the parent component's variable we should pass it through props and the child would return the h1 tag using the props value and add 1 to it. Now, we successfully converted our child component into a pure component.

This achieves both the characteristics of a pure component:

It minds its own business: The child component does not care about any variable or state outside its current scope, the child renders whatever it gets from the parent component.

Same inputs, Same outputs: If the parent component renders 1 or 100 children the output jsx will be the same just that the value passed in props might differ, and there won't be any surprises during rendering. In React, components are allowed to mutate props but this should remain within the component - react calls it - a component’s little secret.

How to keep components pure by keeping changes out of the render phase?

React’s rendering process must always be pure. Components should only return their JSX, and not change any objects or variables that existed before rendering—that would make them impure!

React documentation explains that to keep the components pure, they should not depend on each others’ rendering sequence. You should not mutate any of the inputs that your components use for rendering. That includes props, state, and context.

But in react there will be an event or a need to change the data or update it. This is called a side effect. They execute after the rendering of the component as a side effect of it, event handlers are used for this. Event handlers are functions that React runs when you perform some action—for example when you click a button. Even though event handlers are defined inside your component, they don’t run during rendering! So event handlers don’t need to be pure. When you need to “change things”, you’ll usually want to do it in an event handler. As a last resort, you can useEffect.

How to use Strict Mode to find mistakes in your components?

Although you might not have used them all yet, in React there are three kinds of inputs that you can read while rendering: props, state, and context. You should always treat these inputs as read-only.

When you want to change something in response to user input, you should set state instead of writing to a variable. You should never change preexisting variables or objects while your component is rendering.

React offers a “Strict Mode” in which it calls each component’s function twice during development. By calling the component functions twice, Strict Mode helps find components that break these rules.

Notice how the original example displayed “Guest #2”, “Guest #4”, and “Guest #6” instead of “Guest #1”, “Guest #2”, and “Guest #3”. The original function was impure, so calling it twice broke it. But the fixed pure version works even if the function is called twice every time. Pure functions only calculate, so calling them twice won’t change anything—just like calling double(2) twice doesn’t change what’s returned, and solving y = 2x twice doesn’t change what y is. Same inputs, same outputs. Always.

Strict Mode has no effect in production, so it won’t slow down the app for your users. To opt into Strict Mode, you can wrap your root component into <React.StrictMode>. Some frameworks do this by default.

Conclusion: I have known these concepts but it is refreshing to learn React's thoughts on this, it has improved my thinking while forming a component. By learning this concept, the abstraction process and the logic behind it became much more precise. By following this, optimization of react becomes very effortless as you know what to expect from the component so you can cache it accordingly. Lastly, if you are an experienced developer you should undoubtedly give this a read, it will leave you in awe of how beautiful this react documentation is.

Ps: I have extensively "copied" (might be the right word), react documentation and I highly recommend reading that. click here to read. I wrote this blog to clear my understanding so please correct me if anything seems wrong or add your thoughts in the comments, would love to know your take on this.