Skip to content

Commit 9493350

Browse files
committed
Add useContext questions
1 parent ac72597 commit 9493350

File tree

1 file changed

+168
-5
lines changed

1 file changed

+168
-5
lines changed

README.md

Lines changed: 168 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6132,16 +6132,68 @@ Technically it is possible to write nested function components but it is not sug
61326132
61336133
**[⬆ Back to Top](#table-of-contents)**
61346134
6135-
267. ### How does context works using useContext hook?
6135+
267. ### What is useContext? What are the steps to follow for useContext?
6136+
The `useContext` hook is a built-in React Hook that lets you access the value of a context inside a functional component without needing to wrap it in a <Context.Consumer> component.
6137+
6138+
It helps you **avoid prop drilling** (passing props through multiple levels) by allowing components to access shared data like themes, authentication status, or user preferences.
6139+
6140+
The usage of useContext involves three main steps:
6141+
#### **Step 1 : Create the Context**
6142+
6143+
Use `React.createContext()` to create a context object.
6144+
6145+
```jsx
6146+
import React, { createContext } from 'react';
6147+
6148+
const ThemeContext = createContext(); // default value optional
6149+
```
6150+
6151+
You typically export this so other components can import it.
6152+
6153+
#### **Step 2: Provide the Context Value**
6154+
6155+
Wrap your component tree (or a part of it) with the `Context.Provider` and pass a `value` prop.
6156+
6157+
```jsx
6158+
function App() {
6159+
return (
6160+
<ThemeContext.Provider value="dark">
6161+
<MyComponent />
6162+
</ThemeContext.Provider>
6163+
);
6164+
}
6165+
```
6166+
6167+
Now any component inside `<ThemeContext.Provider>` can access the context value.
6168+
6169+
#### **Step 3: Consume the Context with** `**useContext**`
6170+
6171+
In any functional component **inside the Provider**, use the `useContext` hook:
6172+
6173+
```jsx
6174+
import { useContext } from 'react';
6175+
function MyComponent() {
6176+
const theme = useContext(ThemeContext); // theme = "dark"
6177+
return <p>Current Theme: {theme}</p>;
6178+
}
6179+
```
61366180
61376181
**[⬆ Back to Top](#table-of-contents)**
61386182
61396183
268. ### What are the use cases of useContext hook?
6140-
Some of the common use cases of useContext are listed below,
6184+
The `useContext` hook in React is used to share data across components without having to pass props manually through each level. Here are some common and effective use cases:
61416185
6142-
1. **Theme customizations:** The useContext hook can be used to manage and apply custom themes for an application. That means it allows users to personalize the appearance of the application.
6143-
2. **Support localization:** The context hook is helpful to implement localization by providing translated strings to components based on the user's language/locale preference.
6144-
3. **User authentication:** It can be used to manage user authentication or session status and display user specific information with in components.
6186+
1. **Theme Customization**
6187+
`useContext` can be used to manage application-wide themes, such as light and dark modes, ensuring consistent styling and enabling user-driven customization.
6188+
2. **Localization and Internationalization**
6189+
It supports localization by providing translated strings or locale-specific content to components, adapting the application for users in different regions.
6190+
3. **User Authentication and Session Management**
6191+
`useContext` allows global access to authentication status and user data. This enables conditional rendering of components and helps manage protected routes or user-specific UI elements.
6192+
4. **Shared Modal or Sidebar Visibility**
6193+
It's ideal for managing the visibility of shared UI components like modals, drawers, or sidebars, especially when their state needs to be controlled from various parts of the app.
6194+
5. **Combining with** `**useReducer**` **for Global State Management**
6195+
When combined with `useReducer`, `useContext` becomes a powerful tool for managing more complex global state logic. This pattern helps maintain cleaner, scalable state logic without introducing external libraries like Redux.
6196+
Some of the common use cases of useContext are listed below,
61456197
61466198
**[⬆ Back to Top](#table-of-contents)**
61476199
@@ -6581,6 +6633,117 @@ Technically it is possible to write nested function components but it is not sug
65816633
```
65826634
65836635
**[⬆ Back to Top](#table-of-contents)**
6636+
6637+
283. ### How does useContext works? Explain with an example
6638+
The `useContext` hook can be used for authentication state management across multiple components and pages in a React application.
6639+
6640+
Let's build a simple authentication flow with:
6641+
6642+
* **Login and Logout buttons**
6643+
* Global `AuthContext` to share state
6644+
* Components that can **access and update** auth status
6645+
6646+
**1. Create the Auth Context:**
6647+
6648+
You can define `AuthProvider` which holds and provides `user`, `login()`, and `logout()` via context.
6649+
```js
6650+
// AuthContext.js
6651+
import React, { createContext, useContext, useState } from 'react';
6652+
6653+
const AuthContext = createContext();
6654+
6655+
export function AuthProvider({ children }) {
6656+
const [user, setUser] = useState(null);
6657+
6658+
const login = (username) => setUser({ name: username });
6659+
const logout = () => setUser(null);
6660+
6661+
return (
6662+
<AuthContext.Provider value={{ user, login, logout }}>
6663+
{children}
6664+
</AuthContext.Provider>
6665+
);
6666+
}
6667+
6668+
// Custom hook for cleaner usage
6669+
export const useAuth = () => useContext(AuthContext);
6670+
```
6671+
**2. Wrap Your App with the Provider:**
6672+
6673+
Wrap the above created provider in main `App.js` file
6674+
```js
6675+
// App.js
6676+
import React from 'react';
6677+
import { AuthProvider } from './AuthContext';
6678+
import HomePage from './HomePage';
6679+
import Dashboard from './Dashboard';
6680+
6681+
function App() {
6682+
return (
6683+
<AuthProvider>
6684+
<HomePage />
6685+
<Dashboard />
6686+
</AuthProvider>
6687+
);
6688+
}
6689+
6690+
export default App;
6691+
```
6692+
**3. Home page with login:**
6693+
Read or access user and login details through custom useAuth hook and use it inside home page.
6694+
6695+
```js
6696+
// HomePage.js
6697+
import React from 'react';
6698+
import { useAuth } from './AuthContext';
6699+
6700+
function HomePage() {
6701+
const { user, login } = useAuth();
6702+
6703+
return (
6704+
<div>
6705+
<h1>Home</h1>
6706+
{user ? (
6707+
<p>Welcome back, {user.name}!</p>
6708+
) : (
6709+
<button onClick={() => login('Alice')}>Login</button>
6710+
)}
6711+
</div>
6712+
);
6713+
}
6714+
6715+
export default HomePage;
6716+
```
6717+
6718+
**4. Dashboard with logout:**
6719+
Read or access user and logout details from `useAuth` custom hook and use it inside dashboard page.
6720+
6721+
```js
6722+
// Dashboard.js
6723+
import React from 'react';
6724+
import { useAuth } from './AuthContext';
6725+
6726+
function Dashboard() {
6727+
const { user, logout } = useAuth();
6728+
6729+
if (!user) {
6730+
return <p>Please login to view the dashboard.</p>;
6731+
}
6732+
6733+
return (
6734+
<div>
6735+
<h2>Dashboard</h2>
6736+
<p>Logged in as: {user.name}</p>
6737+
<button onClick={logout}>Logout</button>
6738+
</div>
6739+
);
6740+
}
6741+
6742+
export default Dashboard;
6743+
```
6744+
6745+
**[⬆ Back to Top](#table-of-contents)**
6746+
65846747
## Old Q&A
65856748
65866749
1. ### Why should we not update the state directly?

0 commit comments

Comments
 (0)