aboutsummaryrefslogtreecommitdiff
path: root/src/unstated-next.tsx
blob: 94e9c79b744bf8a5f76473ded7626a1a84a35d81 (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
import React from "react"

export interface ContainerProviderProps {
	children: React.ReactNode
}

export interface Container<Value> {
	Provider: React.ComponentType<ContainerProviderProps>
	useContainer: () => Value
}

export function createContainer<Value>(useHook: () => Value): Container<Value> {
	let Context = React.createContext<Value | null>(null)

	function Provider(props: ContainerProviderProps) {
		let value = useHook()
		return <Context.Provider value={value}>{props.children}</Context.Provider>
	}

	function useContainer(): Value {
		let value = React.useContext(Context)
		if (value === null) {
			throw new Error("Component must be wrapped with <Container.Provider>")
		}
		return value
	}

	return { Provider, useContainer }
}

export function useContainer<Value>(container: Container<Value>): Value {
	return container.useContainer()
}