Created
February 16, 2021 16:36
-
-
Save luizomf/6eeca7c07e29ac5d4da64f2194adb643 to your computer and use it in GitHub Desktop.
React Hook useContext - Curso React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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