Skip to content

Instantly share code, notes, and snippets.

@UberMouse
Last active May 7, 2020 01:07
Show Gist options
  • Save UberMouse/d37c467935275ff6ecabb72072113e48 to your computer and use it in GitHub Desktop.
Save UberMouse/d37c467935275ff6ecabb72072113e48 to your computer and use it in GitHub Desktop.
type TContext = {
state: {
someComputedReduxState: string
},
actions: {
doTheThing: () => void
}
}
const Context = React.createContext<TContext | null>(null);
function Provider(props) {
const someComputedState = useSelector(someSelector);
const doTheThing = useAction(someAction);
return <Context.Provider value={{state: {someComputedState}, actions: {doTheThing}}}>{props.children}</Context.Provider>;
}
const useReduxState = () => useContext(Context);
function Foo() {
const {state, actions} = useReduxState();
return <p onClick={actions.doTheThing}>{state.someComputedReduxState}</p>
}
function FooWithProvider(props) {
return <Provider><Foo {...props} /></Provider>;
}
export { FooWithProvider as Foo, Foo as FooWithoutProvider }
// Then in storybook/testing
<Context.Provider values={{state: {someComputedReduxState: "whatever I want"}, actions: {doTheThing: action("doTheThing")}}>
<FooWithoutProvider />
</Context.Provider>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment