How to implement authentication in React

Implementing authentication is crucial for securing React applications and managing user access to protected resources and routes. As the creator of CoreUI with extensive React development experience since 2014, I’ve built authentication systems for countless enterprise dashboards and admin panels. The most scalable approach uses React Context API to manage global authentication state combined with protected route components. This pattern provides centralized auth logic while maintaining clean component separation and reusability.

Create an authentication context with login/logout methods and use it to protect routes throughout your application.

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

const AuthContext = createContext()

export function AuthProvider({ children }) {
    const [user, setUser] = useState(null)
    const [loading, setLoading] = useState(true)

    const login = async (credentials) => {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(credentials)
        })
        const data = await response.json()
        setUser(data.user)
        localStorage.setItem('token', data.token)
    }

    const logout = () => {
        setUser(null)
        localStorage.removeItem('token')
    }

    useEffect(() => {
        const token = localStorage.getItem('token')
        if (token) {
            // Verify token and set user
        }
        setLoading(false)
    }, [])

    return (
        <AuthContext.Provider value={{ user, login, logout, loading }}>
            {children}
        </AuthContext.Provider>
    )
}

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

This code creates a reusable authentication context that manages user state, login/logout methods, and loading states. The provider wraps your app to make auth data available globally, while the custom hook simplifies access to auth functionality. The useEffect initializes authentication state on app load, checking for existing tokens to maintain login sessions.

Best Practice Note:

This is the authentication architecture we use in CoreUI Pro dashboard templates for enterprise applications. Always implement token refresh logic and secure token storage to maintain robust authentication security.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to get the last element in an array in JavaScript
How to get the last element in an array in JavaScript

How to Add a Tab in HTML
How to Add a Tab in HTML

How to Use JavaScript setTimeout()
How to Use JavaScript setTimeout()

JavaScript Template Literals: Complete Developer Guide
JavaScript Template Literals: Complete Developer Guide

Answers by CoreUI Core Team