Skip to content

Instantly share code, notes, and snippets.

@nico-martin
Created April 6, 2021 19:04
Show Gist options
  • Save nico-martin/d6cffd55cb66192fa689ed58a24d0d1b to your computer and use it in GitHub Desktop.
Save nico-martin/d6cffd55cb66192fa689ed58a24d0d1b to your computer and use it in GitHub Desktop.
A global state with React.Context and React Hooks
import React from 'react';
import { MyContextProvider, useMyContext } from './myContext';
const CompOne = () => {
const [myState, setMyState] = useMyContext();
return (
<div>
<p>
CompOne update:{' '}
<button onClick={() => setMyState({ ...myState, foo: 'baz' })}>
change foo to baz
</button>
</p>
</div>
);
};
const CompTwo = () => {
const [myState] = useMyContext();
return (
<div>
<p>Value of foo: {myState.foo}</p>
</div>
);
};
const App = () => {
return (
<MyContextProvider>
<CompOne />
<CompTwo />
</MyContextProvider>
);
};
import React from 'react';
const MyContext = React.createContext([{}, () => {}]);
export const MyContextProvider = ({ children }) => {
const [myState, setMyState] = React.useState({
hello: 'world',
foo: 'bar',
});
return (
<MyContext.Provider value={[myState, setMyState]}>
{children}
</MyContext.Provider>
);
};
export const useMyContext = () => React.useContext(MyContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment