Pure vs Impure Component in React

Pure vs Impure Component in React

In React, components are the building blocks of user interfaces. They are like functions that receive inputs (props) and return a React element (which describes what should be rendered to the screen).

There are two types of components in React: pure and impure.

Pure Component

Pure components are those that always return the same output given the same input. They do not depend on any external state or other factors, and they do not modify any data outside of their own scope. As a result, they are very predictable and easy to reason about.

Example:

function PureButton(props) {
  const { onClick, children } = props;

  return (
    <button onClick={onClick}>{children}</button>
  );
}

This is an example of a pure component, as it doesn't depend on any external state or other factors. It always returns the same output given the same input (i.e., the props passed to it). It simply renders a button element with an onClick handler and the children passed to it as props.

Impure Component

In contrast, impure components may have side effects, such as modifying external state, interacting with the DOM, or making network requests. They may return different output for the same input, depending on their current state or the state of the application. As a result, they can be more difficult to test and debug.

Example:

class ImpureCounter extends React.Component {
  state = { count: 0 };

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleClick}>Increment</button>
      </div>
    );
  }
}

This is an example of an impure component, as it modifies external state (i.e., the component's state) when the button is clicked. The output of the component changes depending on its current state, and it cannot be predicted solely based on its props.

In general, it's a good practice to try to write as many pure components as possible, as they are easier to reason about and can be optimized for performance by React. However, impure components are sometimes necessary (e.g., for handling user input, making API calls, etc.), and React provides tools for managing their state and lifecycle in a controlled way.