Created
June 24, 2024 20:20
-
-
Save GuiSevero/3babb3d5e3c0b35ded1aaa82fd5b0d50 to your computer and use it in GitHub Desktop.
This file contains 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, { 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