Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React: How to Child component re-render only prop update

I have:

function Parent(){
  const [num, setNum] = useState(0)
  const [someState, setSomeState] = useState({})
  return <div>
      <Child num={num}/>
    </div>
}

function Child({num}) {
  return <div>{num}</div>
}

I want Child re-render only num is updated. If only someState update, Child won’t re-render.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use React.memo and wrap your children component which you want to re-render only when props are changed.

Example:

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

export default function App() {
  const [num, setNum] = useState(0)
  const [someState, setSomeState] = useState({})

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={() => setSomeState({id: 1})}>Change state</button>
      <button onClick={() => setNum(num + 1)}>Change num</button>
      <Child num={num}/>
    </div>
  );
}

const Child = memo(function Child({num}) {
  console.log('child render');
  return <div>{num}</div>
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading