Created
July 25, 2019 06:21
-
-
Save donaldpipowitch/dda6aca890f55e84d251d188c8a8d2cb to your computer and use it in GitHub Desktop.
Share useState with useContext
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useState, useContext, FC } from 'react'; | |
type ContextValue = [boolean, (value: boolean) => void] | undefined; | |
const FullwidthContext = createContext<ContextValue>(undefined); | |
const defaultState = false; | |
export const FullwidthProvider: FC = ({ children }) => { | |
const state = useState(defaultState); | |
return ( | |
<FullwidthContext.Provider value={state}> | |
{children} | |
</FullwidthContext.Provider> | |
); | |
}; | |
export function useFullwidth() { | |
const context = useContext(FullwidthContext); | |
if (!context) | |
throw new Error('useFullwidth must be used within a FullwidthProvider.'); | |
return context; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment