What is Pure Component? How to implement Pure Component?
Generally, If there is a change in state or props values, React component always re-renders the component every time. A pure component is a component that checks whether the state and props values change or not and decide whether to re-render the component or not. That way we improve the application performance.
I will take an example to show you pure component:
I created a component Counter.js and ChildComponent.js and imported ChildComponent in Counter Component.
import {useState} from 'react'
import ChildComponent from './ChildComponent'
const Counter = () => {
const [count,setCount]=useState(0);
return (
<>
{count}
<button onClick={()=>setCount(count+1)}>Increase</button>
<ChildComponent/>
</>
)
}
export default Counter
import React from 'react'
const ChildComponent = () => {
console.log('I am a child component');
return (
<div>ChildComponent</div>
)
}
export default ChildComponent
and now the problem is when Counter Component change the count state ChildComponent also re-render. But ChildComponent didn't change any state or props.
So Pure Component reqired in ChildComponent.
We will use memo to make ChildComponent to make Pure Component.
import React,{memo} from 'react'
const ChildComponent = () => {
console.log('I am a child component');
return (
<div>ChildComponent</div>
)
}
export default memo(ChildComponent)
Now it will work perfect.
