-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcounterContext.js
46 lines (40 loc) · 1.18 KB
/
counterContext.js
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
import React, { useReducer, useContext, useEffect } from 'react';
const initialState = { count: 0 };
export const reducer = (state, action) => {
switch (action.type) {
case 'reset':
return initialState;
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
const CounterContext = React.createContext();
const Counter = () => {
const { store, dispatch } = useContext(CounterContext);
return (
<div>
<p>You clicked {store.count} times</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
);
};
let c = 0;
const Any = () => {
useEffect(() => () => (c = 0), []);
return <p style={{ color: 'red' }}>I should be rendered ONE time but: {++c}</p>;
};
export default function App() {
const [store, dispatch] = useReducer(reducer, initialState);
return (
<CounterContext.Provider value={{ store, dispatch }}>
<Any />
<Counter />
</CounterContext.Provider>
);
}