-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathContextWithMemo.tsx
108 lines (97 loc) · 2.52 KB
/
ContextWithMemo.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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* eslint-disable react-compiler/react-compiler */
import {
createContext,
memo,
useContext,
useReducer,
useRef,
useEffect,
} from 'react';
import type { Reducer } from 'react';
const initialState = {
firstName: 'Harry',
familyName: 'Potter',
};
type State = typeof initialState;
type Action =
| { type: 'setFirstName'; firstName: string }
| { type: 'setFamilyName'; familyName: string };
type Dispatch = (action: Action) => void;
const reducer: Reducer<State, Action> = (state, action) => {
switch (action.type) {
case 'setFirstName':
return { ...state, firstName: action.firstName };
case 'setFamilyName':
return { ...state, familyName: action.familyName };
default:
throw new Error('unexpected action type');
}
};
const PersonContext = createContext<[State, Dispatch]>([
initialState,
() => null,
]);
// eslint-disable-next-line react/display-name
const InnerPersonFirstName = memo(
({ firstName, dispatch }: { firstName: string; dispatch: Dispatch }) => {
const renders = useRef(1);
useEffect(() => {
renders.current += 1;
});
return (
<div>
First Name:
<input
value={firstName}
onChange={(event) => {
dispatch({ type: 'setFirstName', firstName: event.target.value });
}}
/>
(renders:{renders.current})
</div>
);
},
);
const PersonFirstName = () => {
const [state, dispatch] = useContext(PersonContext);
return (
<InnerPersonFirstName firstName={state.firstName} dispatch={dispatch} />
);
};
// eslint-disable-next-line react/display-name
const InnerPersonFamilyName = memo(
({ familyName, dispatch }: { familyName: string; dispatch: Dispatch }) => {
const renders = useRef(1);
useEffect(() => {
renders.current += 1;
});
return (
<div>
Family Name:
<input
value={familyName}
onChange={(event) => {
dispatch({ type: 'setFamilyName', familyName: event.target.value });
}}
/>
(renders:{renders.current})
</div>
);
},
);
const PersonFamilyName = () => {
const [state, dispatch] = useContext(PersonContext);
return (
<InnerPersonFamilyName familyName={state.familyName} dispatch={dispatch} />
);
};
const ContextWithMemo = () => {
const value = useReducer(reducer, initialState);
return (
<PersonContext.Provider value={value}>
<PersonFirstName />
<PersonFamilyName />
</PersonContext.Provider>
);
};
export default ContextWithMemo;