/

React Concept: Purity

React Concept: Purity

In JavaScript, purity refers to the concept of a function or component not causing side effects and always returning the same output for the same input.

A pure function is one that does not mutate objects but only returns a new object. It takes an input and produces an output without changing the input or any other state. When called multiple times with the same input, a pure function will always produce the same output.

In React, this concept of purity is applied to components. A pure component in React is one whose output is solely dependent on its props.

For example, all functional components in React are pure components:

1
2
3
const Button = props => {
return <button>{props.message}</button>
}

Even class components can be pure if their output is solely based on the props:

1
2
3
4
5
class Button extends React.Component {
render() {
return <button>{this.props.message}</button>
}
}

By adhering to the purity concept, React components remain predictable and easier to reason about, improving performance and maintainability.

Tags: React, purity, pure function, pure component