Last active
December 25, 2020 09:49
-
-
Save lovetingyuan/26e9b65ff5a6f83c8893b8d1cf154a68 to your computer and use it in GitHub Desktop.
simple unstated next, useContext to manage state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
interface ContainerProviderProps<State = void> { | |
initialState?: State | |
children: React.ReactNode | |
} | |
const usecontext = React.useContext | |
export default function createContainer<Value, State = void>( | |
usehook: (initialState?: State) => Value, | |
) { | |
const Context = React.createContext<Value | null>(null) | |
function Container(props: ContainerProviderProps<State>): JSX.Element | |
function Container(): Value | |
function Container(props?: ContainerProviderProps<State>): Value | JSX.Element { | |
if (props) { | |
const value = usehook(props.initialState) | |
return React.createElement(Context.Provider, { value }, props.children) | |
} | |
const value = usecontext(Context) | |
if (value === null) { | |
throw new Error('Component must be wrapped with container component returned by `createContainer`.') | |
} | |
return value | |
} | |
if (usehook.name) { | |
Object.defineProperty(Container, 'name', { | |
value: usehook.name, | |
configurable: true | |
}) | |
} | |
return Container | |
} |
Author
lovetingyuan
commented
Dec 23, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment