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.



