Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Last active March 6, 2020 18:10
Show Gist options
  • Save r3dm1ke/8667df70fe6dfb46d11efbd0704229dc to your computer and use it in GitHub Desktop.
Save r3dm1ke/8667df70fe6dfb46d11efbd0704229dc to your computer and use it in GitHub Desktop.
// EXAMPLE WITH CONTEXT
import React, {useContext, useState} from 'react';
const AppContext = React.createContext(null);
const ContextProvider = ({children}) => {
const [counter, setCounter] = useState(0);
const contextValue = {
counter,
setCounter
};
return (
<AppContext.Provider value={contextValue}>
{children}
</AppContext>
);
}
const App = () => {
const {counter, setCounter} = useContext(AppContext);
return (
<ContextProvider>
<Counter />
<ContextProvider/>
);
}
const Counter = () => {
const {counter, setCounter} = useContext(AppContext);
return (
<>
<button onClick={() => setCounter(counter + 1)}>Click me</button>
<p>You clicked me {counter} times</p>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment