How to log out a user in React

Implementing secure user logout in React requires comprehensive cleanup of authentication state, stored tokens, and user data to prevent security vulnerabilities. As the creator of CoreUI with extensive React development experience since 2014, I’ve implemented logout functionality in countless production applications with enterprise security requirements. The most secure approach clears all authentication data from multiple storage locations and redirects users appropriately. This pattern ensures complete session termination while providing clear feedback about logout status.

Create a logout function that clears authentication data from all storage locations and updates application state.

import { useContext } from 'react'
import { useNavigate } from 'react-router-dom'
import { AuthContext } from './AuthContext'

function useAuth() {
    const navigate = useNavigate()
    const { setUser, setIsAuthenticated } = useContext(AuthContext)

    const logout = async () => {
        try {
            // Notify server to invalidate session
            const token = localStorage.getItem('token')
            if (token) {
                await fetch('/api/auth/logout', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                })
            }
        } catch (error) {
            console.error('Logout server error:', error)
            // Continue with client cleanup even if server request fails
        } finally {
            // Clear all authentication data
            localStorage.removeItem('token')
            localStorage.removeItem('user')
            localStorage.removeItem('refreshToken')

            // Clear session storage
            sessionStorage.clear()

            // Clear cookies if using cookie auth
            document.cookie = 'auth=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'

            // Update React state
            setUser(null)
            setIsAuthenticated(false)

            // Redirect to login page
            navigate('/login')
        }
    }

    return { logout }
}

// Usage in component
function UserProfile() {
    const { logout } = useAuth()

    return (
        <div>
            <button onClick={logout} className="logout-button">
                Log Out
            </button>
        </div>
    )
}

This code implements comprehensive logout functionality that handles both client-side and server-side cleanup. It notifies the server to invalidate the session, clears all stored authentication data including tokens and user information, updates React state, and redirects users to the login page. The try-catch ensures cleanup continues even if server communication fails.

Best Practice Note:

This is the secure logout implementation we use in CoreUI dashboard applications for complete session termination. Always implement logout confirmation dialogs for better UX and consider implementing automatic logout for idle sessions in enterprise applications.


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 Migrate from create-react-app to Vite?
How to Migrate from create-react-app to Vite?

How to sleep in Javascript
How to sleep in Javascript

How to Conditionally Add a Property to an Object in JavaScript
How to Conditionally Add a Property to an Object in JavaScript

What is the Difference Between Null and Undefined in JavaScript
What is the Difference Between Null and Undefined in JavaScript

Answers by CoreUI Core Team