skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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:

    1. initial component render
    2. executing useEffect on inital render
    3. component render again because of setState with new value
    4. executing useEffect because state has changed from "" to "Nebila"
    5. component render due to dependency change in useEffect
    6. now we will not execute useEffect because you are setting the same state value, if you initialize a new object inside the ue you will enter an infinite loop!

    Try setting your initial state to "Nebil" useState("Nebil"), the useEffect will only be triggered once on initialRender.

    Here are some helpful references:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search