-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUseContext1.tsx
58 lines (49 loc) · 1.12 KB
/
UseContext1.tsx
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
/*
Context-API
Read values out of the Context
*/
import { createContext, ReactElement, useContext } from 'react';
import { SubTitle } from '../app/components/Headline';
const defaultValue = {
foo: 'default foo',
};
const MyContext = createContext(defaultValue);
const Child1 = () => {
const valueOutOfContext = useContext(MyContext);
return <div>Child1: {JSON.stringify(valueOutOfContext)}</div>;
};
const Child2 = ({ children }: { children: ReactElement }) => {
return (
<>
<div>Child2</div>
{children}
</>
);
};
const Child3 = () => {
const valueOutOfContext = useContext(MyContext);
return <div>Child3: {JSON.stringify(valueOutOfContext)}</div>;
};
export default function UseContext() {
return (
<>
<SubTitle>useContext (read)</SubTitle>
{/* Children consuming context without Provider*/}
{/*}
<>
<Child1 />
<Child2>
<Child3 />
</Child2>
</>
*/}
{/* Children consuming context with Provider*/}
<MyContext.Provider value={{ ...defaultValue }}>
<Child1 />
<Child2>
<Child3 />
</Child2>
</MyContext.Provider>
</>
);
}