Last active
May 14, 2022 19:50
-
-
Save cdaz5/672f7e1d5b8356f21a014e0af94c9456 to your computer and use it in GitHub Desktop.
ctx - custom hook example
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 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 } from 'a-special-place'; | |
const BlandFood = () => { | |
const spice = useSpicyState() | |
return <>{spice}</>; | |
}; | |
const App = () => ( | |
<SpicyCtx.Provider value="scary"> | |
<div> | |
<BlandFood /> | |
</div> | |
</SpicyCtx.Provider> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment