Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
reactjs: a context component function not updating its variable; usestate not working immediately?

I'm working on auth in my app, so I created a context to manage it:

import React, { useState } from "react";

const AuthContext = React.createContext({
    token: "",
    isLoggedIn: false,
    login: (token) => { },
    logout: () => { },
});

export const AuthContextProvider = (props) => {
    const [token, setToken] = useState(null);
    const [userIsLoggedIn, setUserLoggedIn] = useState(false)

    const loginHandler = async (token) => {
        setToken(token);
        setUserLoggedIn(true)
        console.log(userIsLoggedIn)   //prints false
    };

    const logoutHandler = () => {
        setToken(null);
        setUserLoggedIn(false)
    };

    const contextValue = {
        token: token,
        isLoggedIn: userIsLoggedIn,
        login: loginHandler,
        logout: logoutHandler,
    };


    return (
        <AuthContext.Provider value={contextValue}>
            {props.children}
        </AuthContext.Provider>
    );
};

export default AuthContext;

The problem is that when I call context.login('some token') from an outside component and then console.log(context.isLoggedIn) I get false the first time, but if I call context.login('some token') once again I get true. Every succesive time after that I get true now. It might have to do with the fact the "console.log(userIsLoggedIn)" inside the loginHandler says "false" (the first time the context.login is called) even though the setUserLoggedIn is right above it. I think the userIsLoggedIn variable is changed after the context is updated in the component it's used in, but I don't know how to fix that. I will appreciate any help on this

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You cannot rely on the value of userIsLoggedIn to have the value you passed to setUserLoggedIn immediately.

If you want to keep track of the userIsLoggedIn variable, you might consider something like this:

React.useEffect(() => {
  console.log(userIsLoggedIn)
}, [userIsLoggedIn])
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!