Skip to content

Instantly share code, notes, and snippets.

@cdaz5
Last active May 14, 2022 19:50
Show Gist options
  • Save cdaz5/672f7e1d5b8356f21a014e0af94c9456 to your computer and use it in GitHub Desktop.
Save cdaz5/672f7e1d5b8356f21a014e0af94c9456 to your computer and use it in GitHub Desktop.
ctx - custom hook example
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