Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Created August 22, 2020 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shelob9/b476f7f810a773b5d7edbc1f2e84335c to your computer and use it in GitHub Desktop.
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
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