Skip to content

Instantly share code, notes, and snippets.

@GuiSevero
Created June 24, 2024 20:20
Show Gist options
  • Save GuiSevero/3babb3d5e3c0b35ded1aaa82fd5b0d50 to your computer and use it in GitHub Desktop.
Save GuiSevero/3babb3d5e3c0b35ded1aaa82fd5b0d50 to your computer and use it in GitHub Desktop.
import React, { useContext, useState } from 'react';
function useCounterContext() {
const [counter, setCounter] = useState(0);
return {
counter,
setCounter,
} as const;
}
type CounterContext = ReturnType<typeof useCounterContext>;
const Context = React.createContext<CounterContext | null>(null);
export const CounterProvider: React.FC<{ children?: React.ReactNode }> = ({ children }) => {
return <Context.Provider value={useCounterContext()}>{children}</Context.Provider>;
};
export function useCounter() {
const context = useContext(Context);
if (context == null) {
throw new Error(`${useCounter.name} must be used within a ${CounterProvider.name}`);
}
return context;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment