Skip to content

Instantly share code, notes, and snippets.

@yuheiy
Last active August 10, 2023 19:22
Show Gist options
  • Save yuheiy/375bfdce7cf418664386ab6f254c4ee8 to your computer and use it in GitHub Desktop.
Save yuheiy/375bfdce7cf418664386ab6f254c4ee8 to your computer and use it in GitHub Desktop.
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