#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Authentication

Persisting User Authentication Status

When a user logs in to a React app, the token or user info usually lives in component state. State disappears on a page refresh, so the user suddenly looks logged out. Persisting the authentication status means saving enough information outside React, typically in localStorage or a cookie, and reading it back when the app starts so the session survives reloads and new tabs.

What to store and where

After a successful login, the backend normally sends a token (often a JWT) and sometimes an expiry time. You have two common places to keep it.

  • localStorage: easy to read from JavaScript and survives browser restarts. Any script running on your page can also read it, so an XSS bug can leak the token.
  • httpOnly cookie: set by the server and invisible to JavaScript, which protects it from XSS. The browser sends it automatically, so the frontend only needs to know whether the user is logged in, not the token itself.

Learning projects usually start with localStorage because it is simple. For production, many teams prefer httpOnly cookies. Whichever you choose, store the expiry time too, so the app can tell when a saved session is no longer valid.

Restoring the session on startup

A tidy approach is an auth context that reads storage once, when the provider first renders. Passing a function to useState runs it only on the initial render, so there is no flash of the logged-out UI.

import { createContext, useContext, useState } from 'react';

const AuthContext = createContext(null);

function readStoredToken() {
  const token = localStorage.getItem('token');
  const expiresAt = Number(localStorage.getItem('expiresAt'));
  if (!token || Date.now() >= expiresAt) {
    localStorage.removeItem('token');
    localStorage.removeItem('expiresAt');
    return null;
  }
  return token;
}

export function AuthProvider({ children }) {
  const [token, setToken] = useState(readStoredToken);

  function login(newToken, expiresInMs) {
    localStorage.setItem('token', newToken);
    localStorage.setItem('expiresAt', String(Date.now() + expiresInMs));
    setToken(newToken);
  }

  function logout() {
    localStorage.removeItem('token');
    localStorage.removeItem('expiresAt');
    setToken(null);
  }

  const value = { token, isLoggedIn: !!token, login, logout };
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export const useAuth = () => useContext(AuthContext);

Any component can now call useAuth() to check isLoggedIn, and protected pages from the previous lesson keep working after a refresh.

Keeping storage and state in sync

The rule is simple: every time the token changes in state, change it in storage too, and the other way round. That is why login and logout update both. If you only update state, a refresh brings back an old token. If you only update storage, the UI does not re-render.

Multiple tabs are a small extra. The browser fires a storage event in other tabs when localStorage changes, so you can listen for it in a useEffect and log the user out everywhere when they log out in one tab.

Pitfall: trusting a stored token forever

A saved token is only a claim that the user was logged in at some point. It may have expired, or the server may have revoked it. If your app treats any stored token as valid, users see protected screens and then every API call fails with 401. Check the expiry when reading the token, and also handle 401 responses from the API by calling logout(). The next lesson builds on the stored expiry time to log users out automatically.

Key points

  • React state alone is lost on refresh, so save the session outside React.
  • Read storage once with lazy useState initialisation to avoid a logged-out flicker.
  • Update storage and state together in login and logout.
  • Store an expiry time and discard tokens that have passed it.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course