Skip to content

Instantly share code, notes, and snippets.

@rishichawda
Last active May 18, 2019 20:21
Show Gist options
  • Save rishichawda/c1d8e05b553a518629346d73140f8a75 to your computer and use it in GitHub Desktop.
Save rishichawda/c1d8e05b553a518629346d73140f8a75 to your computer and use it in GitHub Desktop.
Complete redux.js - Managing Application state without Redux
import React from "react";
const context = React.createContext();
export const useGlobalState = (initialState = {}, reducer) => {
let init;
let appState = {};
if (typeof initialState === "function") {
init = initialState;
} else {
appState = initialState;
}
const [state, dispatch] = React.useReducer(
reducer,
appState,
init
);
return { ...state, dispatch };
};
export const connect = (mapState, mapDispatch) => {
const componentWithNewProps = (ReactComponent) => {
const componentWithContext = (thisprops) => {
const { dispatch, ...rest } = React.useContext(context);
const mappedProps = mapState ? mapState(rest) : {};
const mappedDispatch = mapDispatch ? mapDispatch(dispatch) : {};
const props = {
...mappedProps,
...mappedDispatch,
};
return <ReactComponent {...props} {...thisprops} />
}
return componentWithContext
}
return componentWithNewProps
}
export const Provider = ({ children, initialValue }) => {
return (
<context.Provider value={{ ...initialValue }}>
{children}
</context.Provider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment