Skip to content

Instantly share code, notes, and snippets.

@mtshrmn
Last active March 23, 2019 20:59
Show Gist options
  • Save mtshrmn/46da15ec26598f4cafab3bcd95a19809 to your computer and use it in GitHub Desktop.
Save mtshrmn/46da15ec26598f4cafab3bcd95a19809 to your computer and use it in GitHub Desktop.
Generating React contexts with ease!
import React, {createContext, useReducer} from "react";
const generateContext = ({initialState = {}, reducer}) => {
const Context = createContext(initialState);
const provideComponent = Component => {
const wrapper = props => {
const [store, dispatch] = useReducer(reducer, initialState);
return (
<Context.Provider value={{store, dispatch}}>
<Component {...props}/>
</Context.Provider>
);
};
return wrapper;
};
return [Context, provideComponent];
};
export default generateContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment