-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathContextApi.jsx
More file actions
58 lines (49 loc) · 1.44 KB
/
ContextApi.jsx
File metadata and controls
58 lines (49 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// ContextApi.jsx
import React, { createContext, useContext, useState } from 'react';
/*
✅ Context API in React:
- Allows you to share state globally without passing props down manually (prop drilling).
- Useful for themes, auth state, language, etc.
🧠 Main Parts:
1. Create context with `createContext()`
2. Wrap components with `Context.Provider`
3. Access context with `useContext()`
*/
// 1. Create Context
const UserContext = createContext();
// 2. Create Provider Component
const UserProvider = ({ children }) => {
const [user, setUser] = useState('Jeevan');
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
};
// 3. Consumer Component (reads context)
const Profile = () => {
const { user } = useContext(UserContext);
return <h3>Welcome, {user}!</h3>;
};
// 4. Updater Component (modifies context)
const ChangeUser = () => {
const { user, setUser } = useContext(UserContext);
return (
<button onClick={() => setUser(user === 'Jeevan' ? 'Ron' : 'Jeevan')}>
Change User Name
</button>
);
};
// 5. Final Combined Component
const ContextApi = () => {
return (
<UserProvider>
<div style={{ padding: '20px' }}>
<h2>React Context API Example</h2>
<Profile />
<ChangeUser />
</div>
</UserProvider>
);
};
export default ContextApi;