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

115
Views
React Context Hook state not changing

I am Creating a simple MERN Authentication, my backend works completely fine, and have tested it with postman, it gives boolean responses when checking for if the user is logged in.

Below is the Router to check the logged-in user, and sending the boolean values to the frontend.

router.get("/loggedIn", (req, res) => {
  try {
    const token = req.cookies.token;
    if (!token) return res.json(false);

    jwt.verify(token, process.env.JWT_SECRET);
    res.send(true);
  } catch (err) {
    res.json(false);
  }
});

In React, I am using Context Hook, to get that response using Axios.

import React, { useState, useEffect, createContext } from "react";
import Axios from "axios";

const AuthContext = createContext();

function AuthContextProvider(props) {
  const [loggedIn, setLoggedIn] = useState(undefined);

  const getLoggedIn = async () => {
    await Axios.get("http://localhost:5000/auth/loggedIn")
      .then((res) => setLoggedIn(res.data))
      .catch((err) => console.log(err));
  };

  useEffect(() => {
    getLoggedIn();
  }, []);

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

export default AuthContext;
export { AuthContextProvider };

I'm using the loggedIn to conditionally render some components, but the value of it or the state always stays false, if I change the state from dev tools conditional rendering works fine.

AuthContext implementation,

const { loggedIn } = useContext(AuthContext);

 {loggedIn === false && (
                <Link className="nav-link" to="/login">
                  <FaUser />
                </Link>
            )}

            {loggedIn === true && (
                <Link className="nav-link" to="/logout">
                  <Button variant="outline-dark">Logout</Button>
                </Link>
            )}

As you can see, I just want to conditionally render a component, but it always returns false

I am new to the ContextHook.

about 4 years ago · Juan Pablo Isaza
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!