What are pure components in React?

June 22, 2024

Pure components are components that produce the same output given the same state and props. In functional components, you can create pure components by using the React.memo() API to wrap the component. This API enhances performance by preventing unnecessary re-renders through a shallow comparison of previous and new props.

However, React.memo() does not compare the previous state with the current state, as functional components inherently avoid unnecessary re-renders when the same state is set again.

The syntax for creating memoized components is as follows:

1const MemoizedComponent = memo(SomeComponent, arePropsEqual?);
2

This example demonstrating how a child component (UserProfile) prevents re-renders when the same props are passed by the parent component (UserForm).

1import { memo, useState } from "react";
2
3const UserProfile = memo(function UserProfile({ username, age }) {
4 return (
5 <>
6 <p>Username: {username}</p>
7 <p>Age: {age}</p>
8 </>
9 );
10});
11
12export default function UserForm() {
13 const [username, setUsername] = useState("");
14 const [age, setAge] = useState("");
15
16 return (
17 <>
18 <label>
19 Username:{" "}
20 <input value={username} onChange={(e) => setUsername(e.target.value)} />
21 </label>
22 <label>
23 Age:{" "}
24 <input value={age} onChange={(e) => setAge(e.target.value)} />
25 </label>
26 <hr />
27 <UserProfile username={username} age={age} />
28 </>
29 );
30}
31

In this example:

  • The UserProfile component is memoized using React.memo(), which ensures it only re-renders when its username or age props change.
  • The UserForm component manages the state for username and age and passes these as props to UserProfile.
  • React.memo() optimizes performance by preventing unnecessary re-renders when the props remain the same.
  • React.memo() is a higher-order component that helps optimize performance by reducing unnecessary renders.

Share this article