Prevent child from re-rendering in React using React.memo

This is the parent component

import React,{useEffect, useState} from 'react';
import './style.css';
import Child1 from './child1';

export default function App() {
    const [change, setChange] = useState(0);
    const onChange = (e)=>{
        setChange(e.target.value)
    }
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <Child1 change={change}/>
            <input type="text" onChange={onChange} value={change} />
            <p>Start editing to see some magic happen :)</p>
            {change}
        </div>
    );
}

The child component

import React, { useEffect, useState } from 'react';
const  Child1 = React.memo((props)=> {
    useEffect(() => {
        console.log('child Update');
    }, [props.change]);
    return (
        <div>
            <h1>Child1</h1>
            {props.change}
        </div>
    );
},(PrevProps, NextProps)=>{PrevProps.change === NextProps.change})
export default Child1

Using React.memo, you can pass first argument as component and second argument as a function which can have two argument PrevProps and NextProps which you can use to compare the change. If the comparison returns true, then the child won’t re-render.

When you overwrite the previous value by copy pasting, it does not re-renders the component i.e. it does not trigger useEffect!

https://react-childupdate.stackblitz.io/

 

 

About the Author

Pravin Varma

Tech Lead at Calsoft

You may also like these