Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

my react app uses useContext to store login and user info, but if I navigate by changing the URL all info is lost and everything resets

import Home from "./pages/home/Home";
import Profile from "./pages/profile/Profile";
import Login from "./pages/login/Login";
import Register from "./pages/register/Register";
import Messenger from "./pages/messenger/Messenger";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
} from "react-router-dom";
import { useContext } from "react";
import { AuthContext } from "./context/AuthContext";

function App() {
  const { user } = useContext(AuthContext);
  console.log(user);
  return (
    <Router>
      <Switch>
        <Route exact path="/">
          {user ? <Home /> : <Register />}
        </Route>
        <Route path="/login">{user ? <Redirect to="/" /> : <Login />}</Route>
        <Route path="/register">
          {user ? <Redirect to="/" /> : <Register />}
        </Route>
        <Route path="/messenger">
          {!user ? <Redirect to="/" /> : <Messenger />}
        </Route>
        <Route path="/profile/:username">
          {!user ? <Redirect to="/" /> : <Profile />}
        </Route>
        <Route path="*">
          {user ? <Profile /> : "404 ERROR: Page does not exists"}
        </Route>
      </Switch>
    </Router>
  );
}

export default App;
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { AuthContextProvider } from "./context/AuthContext";

ReactDOM.render(
  <React.StrictMode>
    <AuthContextProvider>
      <App />
    </AuthContextProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

That's how my app file looks like. Not sure why navigating the app via URL would cause the app to always reset.

For example, the app does have a widget that when clicked will redirect the user to someone else's profile. But If I navigate to that person's profile using the URL instead, everything resets

like image 850
Big Cat Public Safety Act Avatar asked Jan 18 '26 12:01

Big Cat Public Safety Act


1 Answers

React Context doesn't persist when the URL is navigated to directly.

React Router handles URL changes within the application but by changing the URL directly you're telling the browser to load the page again. Your application will need to handle fetching the data required and re-populating React Context if the pages is landed on directly.

This typically involves confirming that the user is logged it (depending on your authentication method this is usually sorted in a cookie) and then fetching any data required by the page.

There are ways of persisting data between sessions but this should be avoided if possible. How can we use the same state across multiple tabs(pages) in react

like image 169
j-petty Avatar answered Jan 20 '26 01:01

j-petty