Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Last active May 30, 2019 12:09
Show Gist options
  • Save andyrichardson/7f7979c4b5c6939b2e2b3c7958d33904 to your computer and use it in GitHub Desktop.
Save andyrichardson/7f7979c4b5c6939b2e2b3c7958d33904 to your computer and use it in GitHub Desktop.
// Context file
export const MyContext = createContext(null);
// Provider abstraction file
import { MyContext } from './context';
export const ProviderAbstraction = ({ children }) => {
const [modalState, setModalState] = useState(false);
return (
<MyContext value={ modalIsOpen: modalState, openModal: () => setModalState(true), closeModal: () => setModalState(false) }>
{children}
</MyContext>
);
}
// Component or hook
import { MyContext } from './context';
export const MyComponent = () => {
const { openModal } = useContext(MyContext);
return (<button onClick={openModal}>Open modal!</button>)
}
// OG Component
import { MyContext } from './context';
const Parent = () => (
<MyContext.Consumer>
{({ openModal }) => (<button onClick={openModal}>Open modal!</button>)}
</MyContext.Consumer>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment