Monday, December 5, 2022

Pure component react | Pure Component in React

 Pure Component in React



In this article we will learn about react pure component with example. first we will under stand the problem then will take a look at solution.

Problem

If we have a value in our state / props and if we are updating our state / props again with same value as old value in state / props. it will re-render our component again. But in actual component should not be render again if same value is again coming in state / props.

if a value already exists in our state or props and we update them again with the same value as the previous value.
It will render our component once again. however, if the same value is again sent in the state or props, the component itself shouldn't be rendered again.

Pure Component in React

It is used to prevent component re-render. react pure components compare the new incoming value of state/props against the previous value of state/props. It won't re-render the component if the old value and the incoming value are similar. The component will be rendered if the old value and the incoming value are both different.


Note:

React pure component is feature that we import from react and this feature is only used in react class component. To achieve same functionality in react functional component we use useMemo hook.




React Pure component example


import React from 'react'

class Student extends React.PureComponent {
constructor()
{
    super()
    this.state = {
        name:"Richard"
    }
}

render() {
return (
    <div className="text-center">
        <h1>Pure Component </h1>
        <h3>My Name is : {this.state.name}</h3>
        <button
            onClick={() => this.setState({name : "Rizwan"})}>
                Update Name
        </button>
    </div>
)}}
export default Student




in above example first time component will render. when we will click update button this will update the value of statue from "Richard" to "Rizwan" so old value and upcoming values are not same due to this component will render again. Now state value  is "Rizwan" so if we press again update button the component will not render again because old value and incoming value of state is same. 

So this is react pure component.

Thanks.



Previous Post
Next Post

post written by:

1 comment: