Last active
July 18, 2023 01:33
-
-
Save Grabber/aae06af51a6217ea1f64c74d18d5407b to your computer and use it in GitHub Desktop.
Experimenting React 18.2.0: Context API
This file contains 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 React, { useState, useReducer, useEffect, useContext } from 'react'; | |
const Ctx = React.createContext(); | |
const Display = () => { | |
return ( | |
<Ctx.Consumer> | |
{ ctx => ( <span>value: {ctx.a}</span> ) } | |
</Ctx.Consumer> | |
); | |
} | |
const DisplayWithUseContext = () => { | |
const ctx = useContext(Ctx); | |
return ( | |
<> | |
<span>value: {ctx.a}</span> | |
</> | |
) | |
} | |
const CtxProvider = ({children}) => { | |
const [a, setA] = useState(123); | |
return ( | |
<> | |
<Ctx.Provider value={{a, setA}}> | |
{children} | |
</Ctx.Provider> | |
</> | |
) | |
} | |
const App = (props) => { | |
const [a, setA] = useState(123); | |
return ( | |
<> | |
<Ctx.Provider value={{a, setA}}> | |
<Display /> | |
<DisplayWithUseContext /> | |
</Ctx.Provider> | |
<CtxProvider> | |
<Display /> | |
<DisplayWithUseContext /> | |
</CtxProvider> | |
</> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code snippet shows how to use the Context API with Provider and Consumer or useContext. It's simple, but took me a few to fully understand all the underlyings and to reduce the code to the minimum as a reference.