-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathindex.tsx
60 lines (52 loc) · 1.43 KB
/
index.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
import React, { useState } from "react"
import { createContainer } from "../src/unstated-next"
import { render } from "react-dom"
function useCounter(initialState = 0) {
const [count, setCount] = useState(initialState)
const decrement = () => setCount(count - 1)
const increment = () => setCount(count + 1)
return { count, decrement, increment }
}
const Counter = createContainer(useCounter)
function useRequiredCounter(step: number) {
const { count } = Counter.useContainer()
const computed = count + step
return { count, step, computed }
}
const RequiredCounter = createContainer(useRequiredCounter)
function CounterDisplay() {
const counter = Counter.useContainer()
return (
<div>
<button onClick={counter.decrement}>-</button>
<span>{counter.count}</span>
<button onClick={counter.increment}>+</button>
</div>
)
}
function RequiredCounterDisplay() {
const { count, step, computed } = RequiredCounter.useContainer()
return (
<div>
Computed Value With Step {step}: {count} + {step} = {computed}
</div>
)
}
function App() {
return (
<Counter.Provider initialState={[]}>
<CounterDisplay />
<Counter.Provider initialState={[2]}>
<div>
<div>
<CounterDisplay />
<RequiredCounter.Provider initialState={[2]}>
<RequiredCounterDisplay />
</RequiredCounter.Provider>
</div>
</div>
</Counter.Provider>
</Counter.Provider>
)
}
render(<App />, document.getElementById("root"))