Even though I have the basics but it seems I'm still struggling, I have this example
const Component = () => {
const [state, setState] = useState("");
useEffect(() => {
console.log("useEffect");
setState("Nebil");
}, [state]);
console.log("component rerender ", state);
};
export default Component;
With the above code I see this output
component rerender
useEffect
component rerender Nebil
useEffect
component rerender Nebil
I wonder why the second time useEffect fires, it updates the state and causes a render, I thought that when the value is equal to "Nebil" and we set the state to "Nebil" since it is a string, this will not render the component. can you please explain this to me?
note: I don't use strictmode
Well, here and explenation on each console.log
component rerender
The default state is ""
useEffect
useEffect is triggered by the default state ""
component rerender Nebil
In useEffect, the state have been changed to "Nebil"
useEffect
since the state is changed, useEffect is triggered by the state "Nebil"
component "rerender" Nebil
since useEffect have been triggered, the function (Component itself is a function) is executed but, even if you see the console.log output, Virtual DOM will not be updated, since it is the same as before, so no additional render will be triggered. You should try to add the return statment and use a developer tool that higligths in green which part of the DOM is updated, I think React dev tools have something to do so.
useEffect is a React Hook that lets you synchronize a component with an external system or in your case you are synchronizing it with your state.
By passing the dependency state to the useEffect, React will compare the state with its previous value. Therefore, because you are setting the state inside the useEffect it will cause the component to re-render because the state change from initial value. Here is what is happening:
Try setting your initial state to "Nebil" useState("Nebil"), the useEffect will only be triggered once on initialRender.
Please make sure to remove strictMode because your components will re-render an extra time to find bugs caused by impure rendering.
I created a sandbox to check the render count https://codesandbox.io/s/long-cookies-s4vjg6?file=/src/App.js
Here are some helpful references:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With