Skip to content

Instantly share code, notes, and snippets.

@cdaz5
Last active May 14, 2022 19:50
Show Gist options
  • Save cdaz5/507c67f2cb20cb128c83789ac7e43c8f to your computer and use it in GitHub Desktop.
Save cdaz5/507c67f2cb20cb128c83789ac7e43c8f to your computer and use it in GitHub Desktop.
import React from 'react';
const SpicyStateCtx = React.createContext(null);
const SpicyApiCtx = React.createContext(null);
// custom provider
const SpicyProvider = ({ children }) => {
const [spice, setSpice] = React.useState("pepper");
const api = React.useMemo(
() => ({
gingerSpice: () => setSpice("ginger"),
sportySpice: () => setSpice("sporty")
}),
[setSpice]
);
return (
<SpicyStateCtx.Provider value={spice}>
<SpicyApiCtx.Provider value={api}>
{children}
</SpicyApiCtx.Provider>
</SpicyStateCtx.Provider>
);
};
// custom hook for the value
export const useSpicyState = () => {
const ctx = React.useContext(SpicyStateCtx);
if (!ctx) {
throw new Error("useSpicyState must be used within the SpicyProvider");
}
return ctx;
};
// custom hook for the api
export const useSpicyApi = () => {
const ctx = React.useContext(SpicyApiCtx);
if (!ctx) {
throw new Error("useSpicyApi 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 } = useSpicyApi();
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