AddisonRedmond
AddisonRedmond

Reputation: 13

React context reverts to initial value when I change routes

I am trying to store a user using react context. I update the state (setUser("new value"), then I change routes. The user value reverts back to what it was originally. Am I not understanding the purpose of context?

App.js listed below

import React from "react";
import { UserProvider } from "./context/user-context";
import "./App.css";
import { BrowserRouter as Switch, Route } from "react-router-dom";

import HomePage from "./pages/homePage/homePage";
import NavBar from "./components/nav-bar/nav-bar.component";
import Login from "./pages/loginPage/loginPage";

function App() {

  return (
     <div className="app-background">
      <UserProvider>
        <NavBar />
        <Switch>
          <Route exact path="/login" component={Login} />
          <Route exact path="/" component={HomePage} />
        </Switch>
      </UserProvider>
    </div>
  );
}

export default App;

user-context listed below

import React, { createContext, useState } from "react";
export const UserContext = createContext();
export const UserProvider = (props) => {
  const [user, setUser] = useState("current state");
  return (
    <UserContext.Provider value={[user, setUser]}>
      {props.children}
    </UserContext.Provider>
  );
};

Upvotes: 1

Views: 1360

Answers (1)

Flavio Li Volsi
Flavio Li Volsi

Reputation: 598

Based on the info gathered from the comments, the solution is to use the react-router built-in navigation functions rather than normal links (which would trigger full page reloads instantiating new states).

Upvotes: 1

Related Questions