InterviewHubPRO
Section Overview
Q281

Question 281 of 445

Part 9: React Hooks Deep Dive (262 - 316)

63%
React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

How does useContext works? Explain with an example

The useContext hook can be used for authentication state management across multiple components and pages in a React application.

Let's build a simple authentication flow with:

  • Login and Logout buttons
  • Global AuthContext to share state
  • Components that can access and update auth status

1. Create the Auth Context:

You can define AuthProvider which holds and provides user, login(), and logout() via context.

js
 // AuthContext.js
 import React, { createContext, useContext, useState } from 'react';
 
 const AuthContext = createContext();
 
 export function AuthProvider({ children }) {
   const [user, setUser] = useState(null);
 
   const login = (username) => setUser({ name: username });
   const logout = () => setUser(null);
 
   return (
     <AuthContext.Provider value={{ user, login, logout }}>
       {children}
     </AuthContext.Provider>
   );
 }
 
 // Custom hook for cleaner usage
 export const useAuth = () => useContext(AuthContext);

2. Wrap Your App with the Provider:

Wrap the above created provider in main App.js file

js
 // App.js
 import React from 'react';
 import { AuthProvider } from './AuthContext';
 import HomePage from './HomePage';
 import Dashboard from './Dashboard';
 
 function App() {
   return (
     <AuthProvider>
       <HomePage />
       <Dashboard />
     </AuthProvider>
   );
 }
 
 export default App;

3. Home page with login: Read or access user and login details through custom useAuth hook and use it inside home page.

js
  // HomePage.js
  import React from 'react';
  import { useAuth } from './AuthContext';

  function HomePage() {
    const { user, login } = useAuth();

    return (
      <div>
        <h1>Home</h1>
        {user ? (
          <p>Welcome back, {user.name}!</p>
        ) : (
          <button onClick={() => login('Alice')}>Login</button>
        )}
      </div>
    );
  }

  export default HomePage;

4. Dashboard with logout: Read or access user and logout details from useAuth custom hook and use it inside dashboard page.

js
 // Dashboard.js
 import React from 'react';
 import { useAuth } from './AuthContext';
 
 function Dashboard() {
   const { user, logout } = useAuth();
 
   if (!user) {
     return <p>Please login to view the dashboard.</p>;
   }
 
   return (
     <div>
       <h2>Dashboard</h2>
       <p>Logged in as: {user.name}</p>
       <button onClick={logout}>Logout</button>
     </div>
   );
 }
 
 export default Dashboard;