aboutsummaryrefslogtreecommitdiff
path: root/example/index.tsx
blob: c967d9d5d3fb1b70b5b16e7f1eebd57dccefaefa (plain) (blame)
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
import React, { useState } from "react"
import { Provider, createContainer } from "../src/unstated"
import { render } from "react-dom"

function useCounter() {
	let [count, setCount] = useState(0)
	let decrement = () => setCount(count - 1)
	let increment = () => setCount(count + 1)
	return { count, decrement, increment }
}

let Counter = createContainer(useCounter)

function CounterDisplay() {
	let counter = Counter.useContainer()
	return (
		<>
			<button onClick={counter.decrement}>-</button>
			<span>{counter.count}</span>
			<button onClick={counter.increment}>+</button>
		</>
	)
}

function App() {
	return (
		<Provider>
			<CounterDisplay />
			<div>
				<div>
					<CounterDisplay />
				</div>
			</div>
		</Provider>
	)
}

render(<App />, document.getElementById("root"))