Skip to content

Instantly share code, notes, and snippets.

@luizomf
Created February 16, 2021 16:36
Show Gist options
  • Save luizomf/6eeca7c07e29ac5d4da64f2194adb643 to your computer and use it in GitHub Desktop.
Save luizomf/6eeca7c07e29ac5d4da64f2194adb643 to your computer and use it in GitHub Desktop.
React Hook useContext - Curso React
import { useContext, createContext, useState } from 'react';
import './App.css';
const globalState = {
title: 'O título que contexto',
body: 'O body do contexto',
counter: 0,
};
const GlobalContext = createContext();
// eslint-disable-next-line
const Div = ({ children }) => {
return (
<>
<H1 />
<P />
</>
);
};
// eslint-disable-next-line
const H1 = () => {
const theContext = useContext(GlobalContext);
const {
contextState: { title, counter },
} = theContext;
return (
<h1>
{title} {counter}
</h1>
);
};
// eslint-disable-next-line
const P = () => {
const theContext = useContext(GlobalContext);
const {
contextState: { body, counter },
setContextState,
} = theContext;
return (
<p
onClick={() => setContextState((s) => ({ ...s, counter: s.counter + 1 }))}
>
{body} {counter}
</p>
);
};
function App() {
const [contextState, setContextState] = useState(globalState);
return (
<GlobalContext.Provider value={{ contextState, setContextState }}>
<Div />
</GlobalContext.Provider>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment