Blog>
Snippets

Using Custom Hooks for Authentication Logic

Create a custom React hook that encapsulates authentication logic, making it reusable across different components that require user authentication.
import { useState, useEffect, useContext, createContext } from 'react';

const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  const login = async (username, password) => {
    // Assume login logic or API call here, setting user if successful
    setUser({ username });
  };

  const logout = () => {
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};
Creates an AuthContext using React Context API and provides an AuthProvider component. The AuthProvider wraps child components, allowing them to access authentication-related data and methods such as login and logout.
import { useContext } from 'react';
import { AuthContext } from './AuthProvider';

export const useAuth = () => {
  const authContext = useContext(AuthContext);
  if (!authContext) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return authContext;
};
Defines a custom hook, useAuth, that allows any component to easily access authentication-related data and methods (user, login, logout) provided by the AuthContext. It ensures the hook is used within an AuthProvider.
import React from 'react';
import { useAuth } from './useAuth';

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

  return (
    <div>
      {user ? (
        <div>
          <p>Welcome, {user.username}!</p>
          <button onClick={logout}>Logout</button>
        </div>
      ) : (
        <button onClick={() => login('user', 'password')}>Login</button>
      )}
    </div>
  );
};

export default ProtectedComponent;
Demonstrates using the useAuth custom hook within a component. This component conditionally renders based on the user's authentication status, showing either a welcome message with a logout button or a login button.