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 ", this will not render the component. can you please explain this to me?
note: I don’t use strictmode
2
Answers
Well, here and explenation on each
console.log
component rerender
The default state is ""
useEffect
useEffect
is triggered by the defaultstate
""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 theconsole.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 thereturn
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.Here are some helpful references: