Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working of `useState` function inside `useEffect` function

I am trying to use useState inside useEffect. I want to access and modify a state inside it( useEffect ), here named as isAuth and according to the new state render the component.

import React, { useState, useEffect } from 'react';

const Authentication = () => {
    const [isAuth, setIsAuth] = useState(false);

    useEffect(() => {
        console.log(isAuth);
        setIsAuth(true);
        console.log(isAuth);
    }, [isAuth]);
    return <div>{isAuth ? <p>True</p> : <p>False</p>}</div>;
};

export default Authentication;

The thing is in console I am getting false, false, true, true.Instead of this console, I expected the 2nd console message to be true. Can someone explain it how it happens and how do I actually change the state before component renders?

like image 772
rohitmi0023 Avatar asked Oct 23 '25 14:10

rohitmi0023


1 Answers

setIsAuth doesn't cause the local variableisAuth to change its value. const data values can't be changed, and even if you defined it as let, that's not what setting state does. Instead, when you set state, the component rerenders. On that new render, the call to useState will return the new value, and you can use that new value for the new render.

The component renders for the first time. Then it runs the effect. The closure for the effect has the local variables from that first render, and your code uses those variables to log the false twice. Since you called set state, a new render will happen, and that new render will have different variables. When it's effect runs, it will log true twice, since that's the values in its closure.

like image 71
Nicholas Tower Avatar answered Oct 25 '25 05:10

Nicholas Tower