forked from vercel/next.js
/
Counter.tsx
57 lines (51 loc) · 1.29 KB
/
Counter.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
import {
useReducer,
useContext,
createContext,
ReactNode,
Dispatch,
} from 'react'
type CounterState = number
type CounterAction =
| {
type: 'INCREASE' | 'DECREASE'
}
| {
type: 'INCREASE_BY'
payload: number
}
const CounterStateContext = createContext<CounterState>(0)
const CounterDispatchContext = createContext<Dispatch<CounterAction>>(
() => null
)
const reducer = (state: CounterState, action: CounterAction) => {
switch (action.type) {
case 'INCREASE':
return state + 1
case 'DECREASE':
return state - 1
case 'INCREASE_BY':
return state + action.payload
default:
throw new Error(`Unknown action: ${JSON.stringify(action)}`)
}
}
type CounterProviderProps = {
children: ReactNode
initialValue?: number
}
export const CounterProvider = ({
children,
initialValue = 0,
}: CounterProviderProps) => {
const [state, dispatch] = useReducer(reducer, initialValue)
return (
<CounterDispatchContext.Provider value={dispatch}>
<CounterStateContext.Provider value={state}>
{children}
</CounterStateContext.Provider>
</CounterDispatchContext.Provider>
)
}
export const useCount = () => useContext(CounterStateContext)
export const useDispatchCount = () => useContext(CounterDispatchContext)