React renders its child components when the parent renders. But if a render is triggered in both the components by a state change in the same batch then a render in parent component doesn’t trigger a render in child.
import React from "react";
import "./style.css";
import {useState, useEffect} from 'react'
export default function App() {
const[change, setChange] = useState(1)
console.count('Count of parent render ')
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>Value of change : {change}</p>
<p>Start editing to see some magic happen :)</p>
<Check onChange={setChange} temp={change}/>
</div>
);
}
function Check({ onChange, temp}) {
const [isOn, setIsOn] = useState(1);
console.count('Count of child renders ')
function handleClick() {
onChange(temp + 5)
setIsOn(isOn+1);
}
return(
<>
<button onClick={handleClick}>Click</button>
<p>Value of isOn:{isOn}</p>
<p>Value of change here : {temp}</p>
</>
)
}
Is there any reason why React performs this way that if the state updates are batched for parent and child, the child doesn’t re-renders separately for the parent render.
Though the code prints the updated value of change in the child component and behave as expected. How does React internally divide between these two scenarios?