React github.com

200 bytes to never think about React state management libraries ever again  ↦

Gotta love when a library is so small that Logbot can JIT inline it in the News and save us precious clicks…

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()
}

Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00