Skip to content

Instantly share code, notes, and snippets.

@chathuranga94
Created July 22, 2019 17:19
Show Gist options
  • Save chathuranga94/e51e01756087fc76b106507461e49e53 to your computer and use it in GitHub Desktop.
Save chathuranga94/e51e01756087fc76b106507461e49e53 to your computer and use it in GitHub Desktop.
import React, { useState, useContext } from 'react';
const AppContext = React.createContext({});
const App = () => {
const [lang, setLang] = useState('en');
const [color, setColor] = useState('blue');
const store = {
lang: { get: lang, set: setLang },
color: { get: color, set: setColor }
};
return (
<AppContext.Provider value={store}>
<LanguagePicker />
<Menu />
</AppContext.Provider>
);
}
const Menu = () => <MenuItem />;
const LanguagePicker = () => {
const context = useContext(AppContext);
return (
<div>
<button onClick={() => context.lang.set('en')}>English</button>
<button onClick={() => context.lang.set('fr')}>French</button>
</div>
);
}
const MenuItem = () => {
const context = useContext(AppContext);
return (
<div>
<p>Theme colour: {context.color.get}</p>
<p>Locale: {context.lang.get}</p>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment