ReactJS

    Pure vs Impure Component in React


    Introduction

    Components are the basic units of user interface development in React. They behave identically to functions, accepting in inputs (props) and producing a React element that specifies what should be displayed on the screen.

    React has two different kinds of components: impure and pure.

    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.

    function PureButton(props) {const { onClick, children } = props;return (<button onClick={onClick}>{children}</button>);}

    Since it is unaffected by any external state or additional variables, this is an instance of a pure component. When given the same input (i.e., the props sent to it), it consistently produces the same output. The kids are supplied to it as props, and it merely generates a button element with an onClick handler.

    Impure Component

    Impure components, on the other hand, might alter external state, communicate with the DOM, or send network requests, among other unintended consequences. Depending on their present state or the application's state, they might offer multiple results for the same input. They may therefore be more challenging to test and debug.

    import React, { useState } from "react";const ImpureCounter = () => {const [count, setCount] = useState(0);const handleClick = () => {setCount(count + 1);};return (<div><p>Count: {count}</p><button onClick={handleClick}>Increment</button></div>);};export default ImpureCounter;

     

    This is an example of an impure component since pressing the button alters the external state, or the state of the component. Because the component's output fluctuates depending on its current state, it cannot be estimated just from its props.

    conclusion

    Writing as many pure components as you can is generally a good idea because React can optimize them for performance and they are simpler to understand. React offers methods for controlling the state and lifecycle of impure components, which are occasionally required (for example, processing user input, making API calls, etc.).

    Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise. 

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    ReactJS

    Related Center Of Excellence