Home > Enterprise >  How to avoid unnecessary re-render of a component in React?
How to avoid unnecessary re-render of a component in React?

Time:11-13

I have this case:

const Parent = () => {
  
  const [value, setValue] = useState('');
  
  return <>
    <Child1 value={value} />
    <Child2 setValue={setValue} />
    </>
  
}

but every time setValue of Child2 is getting called, Child2 re-renders although its props have not been changed (Child1 re-renders also, but this is the expected behavior since prop value changed).

How to fix this ?

CodePudding user response:

This is the purpose of Edit how-to-avoid-unnecessary-re-render-of-a-component-in-react

Sandbox code:

import { memo, useEffect, useState } from "react";
import "./styles.css";

const Child1 = ({ value }) => {
  useEffect(() => console.log("Child 1 rendered"));
  return <div>Child1: {value}</div>;
};

const Child2 = ({ id, setValue }) => {
  useEffect(() => console.log(`${id} rendered`));
  return (
    <div>
      {id}: <input type="text" onChange={(e) => setValue(e.target.value)} />
    </div>
  );
};

const Child2wMemo = memo(Child2);

const Parent = () => {
  const [value, setValue] = useState("");

  return (
    <>
      <Child1 value={value} />
      <Child2 id="Child 2" setValue={setValue} />
      <Child2wMemo id="Child 2 with Memo" setValue={setValue} />
    </>
  );
};

export default function App() {
  return (
    <div className="App">
      <Parent />
    </div>
  );
}

enter image description here

  • Related