This is my code snippet (https://i.stack.imgur.com/WwxNG.png) this is the output for the above code (https://i.stack.imgur.com/Ha08w.png) Can someone explain me why this third rendering being printed in the console.
I have been stuck with this condition and because of this I can't carry on with my React.js Learning.
CodePudding user response:
Please post relevant code/output/errors here, pictures of them. The output makes sense, here's what each one is:
Rendering <---------- initial render when the component mounts
Inside Use Effect <-- after rendering, effects run. This is the effect running on mount
Rendering <---------- This happens because you update state in the effect, triggering a re-render
Inside Use Effect <-- Because you have `count` as an effect dependency, the value has changed (was 10, then you set to 11) and so it calls `setCount(11)` again, triggering another re-render
Rendering <---------- This is the render from that second effect run
And that's it. Because the count was 11, and the second effect again set it to 11, it didn't actually change that time, so the effect doesn't run and there's no more renders or effect executions. Your confusion may be from setting a state value to a hard-coded value, but also having the state value as an effect dependency - this produces a second effect execution that's not really needed in this case
CodePudding user response:
You are giving the dependency count in the useEffect.
import React from "react";
import "./style.css";
export default function App() {
const [count, setCount] = React.useState(10);
console.log("Rendering");
React.useEffect(() => {
console.log("Inside the useeffect")
setCount(11);
}, []);
return (
<div>
<p>{count}</p>
</div>
);
}