Skip to content

Instantly share code, notes, and snippets.

@nico-martin
Created Apr 6, 2021
Embed
What would you like to do?
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