Our project uses React's Context API for managing authentication state. The AuthContext.jsx file defines AuthContext
and its provider AuthProvider
. This document will guide you on how to use AuthContext
effectively in our project.
AuthContext
provides the following state and functionality:isAuthenticated
: A boolean indicating if the user is authenticated.setIsAuthenticated
: A function to update theisAuthenticated
state.userData
: An object containing user data. This isnull
if the user is not authenticated.logout
: A function to handle user logout.
To use AuthContext
in a component:
-
Import the Context
import { AuthContext } from 'path/to/AuthContext';
-
Consume the Context Use the
useContext
hook to access the context values.const { isAuthenticated, userData, logout } = useContext(AuthContext);
-
Example Usage
- Checking Authentication Status
if (isAuthenticated) { console.log('User is authenticated'); }
- Using User Data
- example file: Dashboard.jsx
console.log(userData.role, userData.name, userData.email);
- example file: Dashboard.jsx
- Handling Logout
const handleLogout = () => { logout(); };
- Checking Authentication Status
- Use Context Sparingly: Avoid overusing the context in components where it's not needed.
- Update Auth State Responsibly: Only use provided functions (
login
,logout
,checkAuthStatus
) to update authentication-related state. - Securing Routes: For routes that require authentication, use
isAuthenticated
to conditionally render components or redirect users.
- Our component tree is already wrapped with
AuthProvider
in the root of your application, do not try to change theAuthProvider
inAppRouts.jsx
! - Always test the authentication flows after making changes related to authentication.
For any questions or further clarifications, feel free to reach out to the team.