-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseContextImplementation.js
More file actions
84 lines (65 loc) · 1.68 KB
/
Copy pathuseContextImplementation.js
File metadata and controls
84 lines (65 loc) · 1.68 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// CounterProvider.js
import React, { useState } from 'react';
import { createContext } from 'react';
export const CounterContext = createContext();
const CounterProvider = ({ children }) => {
const [count1, setCount1] = useState(0);
const [count2, setCount2] = useState(0);
const incrementCount1 = () => setCount1(prev => prev + 1);
const incrementCount2 = () => setCount2(prev => prev + 1);
return (
<CounterContext.Provider
value={{
count1,
count2,
incrementCount1,
incrementCount2,
}}
>
{children}
</CounterContext.Provider>
);
};
export default CounterProvider;
// Button1.js
import React, { useContext } from 'react';
import CounterContext from './CounterContext';
const Button1 = () => {
const { count1, incrementCount1 } = useContext(CounterContext);
return (
<button onClick={incrementCount1}>
Button 1 Count: {count1}
</button>
);
};
export default Button1;
// Button2.js
import React, { useContext } from 'react';
import CounterContext from './CounterContext';
const Button2 = () => {
const { count2, incrementCount2 } = useContext(CounterContext);
return (
<button onClick={incrementCount2}>
Button 2 Count: {count2}
</button>
);
};
export default Button2;
// App.js
import React from 'react';
import CounterProvider from './CounterProvider';
import Button1 from './Button1';
import Button2 from './Button2';
const App = () => {
return (
<CounterProvider>
<div style={{ padding: '20px' }}>
<h2>Shared Counter via useContext</h2>
<Button1 />
<br /><br />
<Button2 />
</div>
</CounterProvider>
);
};
export default App;