Last active
August 10, 2023 19:22
-
-
Save yuheiy/375bfdce7cf418664386ab6f254c4ee8 to your computer and use it in GitHub Desktop.
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 type { Dispatch, DispatchWithoutAction, ReactNode, SetStateAction } from 'react'; | |
import { useCallback, useState } from 'react'; | |
/** | |
* The implement a hooks version of React PowerPlug’s `<State />`. | |
* https://renatorib.github.io/react-powerplug/#/docs-components-state | |
* | |
* @example | |
* <State initial={false}> | |
* {({ state: isOpen, setState: setOpen }) => ( | |
* <> | |
* <button type="button" onClick={() => setOpen(true)}>Open</button> | |
* <Popover isOpen={isOpen} onOpenChange={setOpen}>...</Popover> | |
* </> | |
* )} | |
* </State> | |
*/ | |
export function State<S>({ | |
initial: initialState, | |
children, | |
}: { | |
initial: S | (() => S); | |
children: (props: { | |
state: S; | |
setState: Dispatch<SetStateAction<S>>; | |
resetState: DispatchWithoutAction; | |
}) => ReactNode; | |
}) { | |
const [state, setState] = useState(initialState); | |
const resetState = useCallback(() => setState(initialState), [initialState]); | |
return children({ | |
state, | |
setState, | |
resetState, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment