Skip to content

Instantly share code, notes, and snippets.

@Grabber
Last active July 18, 2023 01:33
Show Gist options
  • Save Grabber/aae06af51a6217ea1f64c74d18d5407b to your computer and use it in GitHub Desktop.
Save Grabber/aae06af51a6217ea1f64c74d18d5407b to your computer and use it in GitHub Desktop.
Experimenting React 18.2.0: Context API
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;
@Grabber
Copy link
Author

Grabber commented Mar 31, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment