FrontendDeveloper.in

React question detail

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.

// 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

// 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.

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

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

return (
<h1>Home</h1>
{user ? (
) : (
<button onClick={() => login('Alice')}>Login</button>
)}
);
}

export default HomePage;

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

// 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 (
<h2>Dashboard</h2>
<button onClick={logout}>Logout</button>
);
}

export default Dashboard;
Back to all React questions
Get LinkedIn Premium at Rs 399