Last active
May 14, 2022 19:50
-
-
Save cdaz5/c107b4ef4b972de4d82ba57d910de362 to your computer and use it in GitHub Desktop.
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 React from 'react'; | |
const SpicyCtx = React.createContext(null); | |
// custom provider | |
export const SpicyProvider = ({ children }) => { | |
const [spice, setSpice] = React.useState("scary"); | |
const api = { | |
gingerSpice: () => setSpice("ginger"), | |
sportySpice: () => setSpice("sporty") | |
}; | |
return ( | |
<SpicyCtx.Provider value={{ spice, ...api }}>{children}</SpicyCtx.Provider> | |
); | |
}; | |
// custom hook | |
export const useSpicyState = () => { | |
const ctx = React.useContext(SpicyCtx); | |
if (!ctx) { | |
throw new Error("useSpicyState must be used within the SpicyProvider"); | |
} | |
return ctx; | |
}; | |
// in another file | |
import { useSpicyState, SpicyProvider } from 'a-special-place'; | |
const BlandFood = () => { | |
const { spice } = useSpicyState(); | |
return <>{spice}</>; | |
}; | |
const SpiceButtons = () => { | |
const { sportySpice, gingerSpice } = useSpicyState(); | |
return ( | |
<> | |
<button type="button" onClick={sportySpice}> | |
Sporty | |
</button> | |
<button type="button" onClick={gingerSpice}> | |
Ginger | |
</button> | |
</> | |
); | |
}; | |
const App = () => ( | |
<SpicyProvider> | |
<div> | |
<BlandFood /> | |
<SpiceButtons /> | |
</div> | |
</SpicyProvider> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment