I have two blocks of React code and I am trying to understand how the rendering works.
const { useState, useEffect } = React;
function A({ children }) {
console.log("A");
const [state, setState] = useState(0);
useEffect(() => {
setState((state) => state + 1);
}, []);
return children;
}
function B() {
console.log("B");
return <C />;
}
function C() {
console.log("C");
return null;
}
function D() {
console.log("D");
return null;
}
function App() {
console.log("App");
return (
<div>
<A>
<B />
</A>
<D />
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.development.js"></script>
Output of above code is:
App A B C D A
I was expecting the output would be: App A B C D A B C suggesting that B and C components would be re-rendered as their parent(A)'s state had changed. Why is the output just App A B C D A?
I have another code as follows:
const { useState, useEffect } = React;
function A({ children }) {
console.log("A");
return children;
}
function B() {
console.log("B");
return <C />;
}
function C() {
console.log("C");
return null;
}
function D() {
console.log("D");
return null;
}
function App() {
const [state, setState] = useState(0);
useEffect(() => {
setState((state) => state + 1);
}, []);
console.log("App");
return (
<div>
<A>
<B />
</A>
<D />
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.development.js"></script>
Output in the above code is as per my expectation:
App A B C D App A B C D
What is the problem in my understanding?