What's purity in React?

Pure function

In JavaScript, a function is considered pure if the return value is determined by its input values only and is always the same for the particular input values.

The same concept can be applied to React components, therefore a React component is said to be pure if it renders the same output for the same input (props).

In React, we differentiate between functional and class components. While all functional components are always pure components, class components are considered pure if their output depends only on received props and not on their own state.

When a class-based component renders only based on props and is pure, it doesn’t need to re-render if the props have not changed.

Example of pure React component

Here is an example of a pure React class-based component:

class Message extends React.Component {
render() {
return <p>{this.props.message}</p>
}
}

Example of impure React component

Here is an example of an impure React class component in which the component gets re-rendered every time setState is called:

class Counter extends React.Component {
constructor() {
super();
this.state = {
counter: 0
}
setInterval(() => {
this.setState({
counter: 0
});
}, 1000);
}
render() {
return <p>{this.state.counter}</p>
}
}

What is React.PureComponent?

React.PureComponent is similar to React.Component, but different in a way that it doesn’t implement shouldComponentUpdate(). Rather, it implements it with a shallow prop and state comparison. It’s particularly useful in situations in which we might need a performance boost.

React.PureComponent considers the updated values of the component’s props and state. If updated values are the same as previous values, re-rendering is not triggered.

Free Resources