Created
August 22, 2020 14:27
-
-
Save Shelob9/b476f7f810a773b5d7edbc1f2e84335c to your computer and use it in GitHub Desktop.
Simple React context example, with TypeScript. See: https://codesandbox.io/s/react-context-tldr-bey3y
This file contains 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
const RoyContext = React.createContext<{ | |
hi: boolean; | |
setHi: (set: boolean) => void; | |
}>(null); | |
const RoyProvider = ({ children }) => { | |
const [hi, setHi] = useState<boolean>(true); | |
return ( | |
<RoyContext.Provider value={{ hi, setHi }}>{children}</RoyContext.Provider> | |
); | |
}; | |
const IsHi = () => { | |
const { hi } = useContext(RoyContext); | |
return <div>{hi}</div>; | |
}; | |
const SomethingElse = () => { | |
return ( | |
<div> | |
<IsHi /> | |
</div> | |
); | |
}; | |
const App = () => ( | |
<RoyProvider> | |
<SomethingElse /> | |
</RoyProvider>; | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment