Skip to content

Instantly share code, notes, and snippets.

@ricca509
Created March 15, 2020 22:58
Show Gist options
  • Save ricca509/10be444431f3ad831ef7a8477578e113 to your computer and use it in GitHub Desktop.
Save ricca509/10be444431f3ad831ef7a8477578e113 to your computer and use it in GitHub Desktop.
import { createElement, createContext, useReducer, useContext } from "react";
const Context = createContext();
export const ContextProvider = Context.Provider;
export const useStore = (reducer, initialState = {}) => {
const [state, dispatch] = useReducer(reducer, initialState);
const getState = () => state;
return { getState, dispatch };
};
export const connect = (
mapStateToProps = () => ({}),
mapDispatchToProps = () => ({})
) => Component => ownProps => {
const { getState, dispatch } = useContext(Context);
const stateProps = mapStateToProps(getState(), ownProps);
const dispatchProps = mapDispatchToProps(dispatch, ownProps);
const props = { ...ownProps, ...stateProps, ...dispatchProps, dispatch };
return createElement(Component, props, null);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment