Skip to content

context auth

Paulo Gomes da Cruz Junior edited this page Jun 16, 2026 · 3 revisions

Auth Context

The Auth Context manages authentication state and user information across your React application. It provides a centralized way to access the current user, authentication status, and related actions such as login and logout.

Usage

Provider

Wrap your application (or a subtree) with the AuthProvider to enable authentication context:

import { AuthProvider } from 'src/context/auth/AuthProvider';

<AuthProvider>
  {/* your app components */}
</AuthProvider>

Hook

Use the useAuth hook to access authentication state and actions from any component within the provider:

import { useAuth } from 'src/context/auth/useAuth';

const { user, isAuthenticated, login, logout } = useAuth();

if (!isAuthenticated) {
  return <button onClick={login}>Login</button>;
}

return (
  <div>
    <span>Welcome, {user?.name}</span>
    <button onClick={logout}>Logout</button>
  </div>
);

API

useAuth()

Returns an object with:

  • user: User | null — The current authenticated user, or null if not logged in.
  • isAuthenticated: boolean — Whether the user is authenticated.
  • login: () => void — Function to initiate login.
  • logout: () => void — Function to log out the user.

Example

import { useAuth } from 'src/context/auth/useAuth';

function Profile() {
  const { user, logout } = useAuth();

  if (!user) return null;

  return (
    <div>
      <h2>{user.name}</h2>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

When to Use

  • To protect routes or components that require authentication.
  • To display user information or authentication status in the UI.
  • To provide login and logout functionality throughout your app.

See also:

Waste Plus Wiki

Home

Architecture

Codes

Decisions

Knowledge Base

Development

Changes

Clone this wiki locally