In this blog post, we aim to delve into pure components in React, shedding light on their nature, functionality, and advantages. Furthermore, we will furnish React-based illustrations of pure components and guide you through the process of creating them.
Check out our ReactJS Course video on YouTube:
What is a Pure Component in React?
Let’s answer, what is a pure component in React? Pure components in React are a type of component that only re-renders when its props or state change. They are also referred to as “stateless components” or “dumb components”. Pure components are a way to optimize the performance of your React application by reducing unnecessary re-renders.
The React.PureComponent class is responsible for creating pure components. It shares similarities with the React.Component class, but it goes a step further by implementing a shouldComponentUpdate() method. This method automatically verifies whether there have been any changes in the component’s props or state before triggering a re-render. If no changes are detected, the component remains unchanged, leading to enhanced performance.
How to Create a Pure Component in React?
In React, you can create pure components by using function components and ensuring that they are stateless and don’t have any side effects. Pure components are ideal for rendering based on props and are not affected by changes in the component’s state or other external factors. Here’s an example of creating a pure component in React:
import React from 'react';
const PureComponent = ({ name }) => {
return <div>Hello, {name}! This is a pure component.</div>;
};
export default PureComponent;
In the code above, we define a functional component called Pure Component that takes a name prop and renders a simple greeting message. Since this component only relies on the prop value and doesn’t have any internal state or side effects, it can be considered a pure component.
Get 100% Hike!
Master Most in Demand Skills Now!
How do Pure Components Work in React?
Pure components employ a should ComponentUpdate() method to actively compare the current props and state of the component with their previous counterparts. If no changes are detected, the component refrains from re-rendering. This mechanism is referred to as “shallow comparison”.
In shallow comparison, the comparison of props and state occurs only at the top level. Complex objects or arrays within the props or state will not be examined for changes through shallow comparison. To address this, a more sophisticated comparison approach may be required.
Pure components prove valuable when dealing with components that undergo frequent re-rendering while experiencing no alterations in their props or state. By implementing the shouldComponentUpdate() method, unnecessary re-renders can be avoided, thereby enhancing the performance of your React application.
Here’s an example code snippet that demonstrates the working of pure components in React:
import React, { PureComponent } from 'react';
class MyComponent extends PureComponent {
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.text}</p>
</div>
);
}
}
// Usage:
const App = () => {
const title = 'Welcome to my App';
const text = 'This is a sample text.';
return (
<div>
<MyComponent title={title} text={text} />
</div>
);
};
export default App;
In the provided example, the MyComponent class extends the PureComponent class, a built-in class provided by React. By extending PureComponent, the shouldComponentUpdate() method is automatically implemented for shallowly comparing the component’s props and state.
When the MyComponent receives new props or updates its state, React conducts a shallow comparison to determine if a re-rendering is needed. If the new props and state are found to be shallowly equal to the previous ones, React optimizes performance by skipping the re-rendering process. This mechanism ensures efficiency in the component’s rendering and enhances overall application performance.
Advantages of Using Pure Components in React
There are several advantages of using pure components in your React application. Below mentioned are the benefits of using pure components in React:
- Improved Performance: By reducing the number of unnecessary re-renders, pure components can significantly improve the performance of your React application.
- Easier to Reason About: Pure components are easier to reason about and test since they only depend on their props or state.
- Better Code Organization: By separating your components into pure and impure components, you can better organize your code and improve its maintainability.
- Code Reusability: Pure components are highly reusable since they only depend on their props. This can help reduce code duplication and make your code more modular.
- Improved Debugging: Since pure components have a clear separation of concerns, it can be easier to debug issues in your code.
Examples of Pure Components in React
React emphasizes the significance of pure components, which actively enhance code performance and maintainability. This section delves into various illustrative examples of pure components in React.
- Functional Components: Functional components are a type of pure component in React that take props as input and return the JSX to render, they do not have any internal state or side effects. This makes them highly reusable and easy to reason about. Here’s an example of a functional component that takes a prop called “message” and renders it in a paragraph tag:
function Message(props) {
return <p>{props.message}</p>;
}
- Stateless Components: Stateless components are another type of pure component in React that is similar to functional components. They are defined using the arrow function syntax and only take props as input. Here’s an example of a stateless component that takes a prop called “name” and renders it in a heading tag:
const Name = (props) => <h1>{props.name}</h1>;
- Memo Components: In React, you can utilize Memo components to enhance your application’s performance. Memo components, a specific type of pure component, operate similarly to functional components but incorporate an additional optimization layer. This optimization ensures that the component is only re-rendered when its props undergo changes. Below is an example of a memo component that accepts a prop named “count” and renders it within a paragraph tag:
const Count= React.memo((props) => {
return <p>{props.count}</p>;
});
- Pure Class Components: If a class component in React relies solely on its props or state, it can also function as a pure component. To create a pure class component, one can extend the PureComponent class instead of the standard Component class. Here’s an instance of a pure class component that accepts a prop named “title” and renders it within a heading tag
class Title extends React.PureComponent {
render() {
return <h1>{this.props.title}</h1>;
}
}
Pure components, including functional components, stateless components, memo components, and pure class components, serve as prime examples within React that cater to various scenarios. By familiarizing yourself with the implementation and usage of pure components in your React application, you can compose code that is more efficient and scalable.
Differences between Pure and Impure Components in React
Let’s understand the difference between pure and impure components in React:
Pure Components | Impure Components |
Pure components are stateless and do not have any internal state. | Impure components can have internal state and manage their own data. |
Pure components are primarily used for rendering UI based on props only. | Impure components can perform side effects, such as making API calls or modifying global state. |
Pure components have better performance as they can be optimized by React’s reconciliation algorithm. They only re-render when their props change. | Impure components may re-render more frequently, as their internal state changes can trigger re-rendering. |
Pure components are easy to reason about and test, as they have a deterministic behavior based on their props. | Impure components may have more complex logic and dependencies, making them harder to test and reason about. |
Example of a pure component:
javascript import React from 'react';
const PureButton = ({ onClick, text }) => { return ( <button onClick={onClick}>{text}</button> ); };
export default PureButton;
This pure component, ‘PureButton,’ is a functional component that accepts two props: ‘onClick’ and ‘text.’ It renders a button element with the provided ‘text’ as the button label. The ‘onClick’ prop is assigned as the click event handler for the button. | Example of an impure component:
javascript import React, { useState } from 'react';
const ImpureCounter = () => { const [count, setCount] = useState(0);
const incrementCount = () => { setCount(count + 1); };
return ( <div> <p>Count: {count}</p> <button onClick={incrementCount}>Increment</button> </div> ); };
The ‘ImpureCounter’ component is implemented as a functional component using the ‘useState’ hook to manage its internal state. It declares a state variable called ‘count’ and initializes it with the value 0. The component renders a paragraph element displaying the current value of ‘count,’ and a button that triggers the ‘incrementCount’ function when clicked. |
Conclusion
Pure components are a crucial optimization technique in React that can significantly enhance application performance. They are stateless and only re-render when there are changes in their props or state, resulting in fewer unnecessary re-renders and saved computational resources. In this blog post, we discussed the concept of pure components, their functioning, and their benefits.
We also provided React examples and demonstrated how to create them. By leveraging pure components in your React application, you can enhance performance, organization, and reusability. Furthermore, pure components are easier to comprehend and test, facilitating the development of robust and maintainable code. If you seek to optimize your React application’s performance, adopting pure components is a straightforward and effective approach that delivers an improved user experience.