Skip to content

Instantly share code, notes, and snippets.

@csantiago132
Last active February 25, 2020 01:52
Show Gist options
  • Save csantiago132/e1634d440708ee5fbbb05e4bba63180c to your computer and use it in GitHub Desktop.
Save csantiago132/e1634d440708ee5fbbb05e4bba63180c to your computer and use it in GitHub Desktop.
import * as React from 'react';
import reducer from './path to the object containing the reducers/';
import { combineReducer } from './path to combineReducer function';
const AppStateProvider = React.createContext({});
const ContextProvider = ({ children }) => {
const reducers = React.useCallback(() => {
return combineReducer(reducer);
}, [combineReducer]);
// call the function to get initial state and global reducer
const [initialState, mainReducer] = reducers();
// setup useReducer with the returned value of the reducers function
const [state, dispatch] = React.useReducer(mainReducer, initialState);
// pass in the returned value of useReducer
const contextValue = React.useMemo(() => ({ state, dispatch }), [state, dispatch]);
return <AppStateProvider.Provider value={contextValue}>{children}</AppStateProvider.Provider>;
};
export { ContextProvider, AppStateProvider as ContextConsumer };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment