I have got 2 pieces of code one is using independent state in child and the other one with state being send out as props like this in my " sent as props " version.
function App() {
const [isChanged, setIsChanged] = React.useState(false);
const [i, setI] = React.useState(0);
React.useEffect(() => {
console.log("USEEFFECT");
setTimeout(() => {
setIsChanged(true);
}, 2000);
}, []);
return (
<div className="App zx">
{isChanged && <h1>Hello CodeSandbox with outter states</h1>}
<Change set={setI} i={i} />
</div>
);
}
the second one with the exception of having states inside <Change />
as such :
function Change() {
const [i, setI] = React.useState(0);
let rnd = 9;
if (i !== rnd) {
setI(i + 1);
}
console.log(i);
The version in which state is managed inside the child, the component runs twice and I get the log two times in a row but in the one with passed down state as props I get the component running once as desired.
- Why is this happening and which one is the correct practice ?
- When can I safely use state in a child component without worrying about re-renders ?
- Is there a way to avoid the re-render in the first version so I get the same results despite using state in the child component ? If so please provide me with a sample.
To reproduce,
- Props version : https://codesandbox.io/s/heuristic-driscoll-9m1pl
- state in child version : https://codesandbox.io/s/confident-shockley-btjg6