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.
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>
});