Skip to content

Instantly share code, notes, and snippets.

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