added orai
This commit is contained in:
31
20250312/my-app/app/components/CounterContext.tsx
Normal file
31
20250312/my-app/app/components/CounterContext.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import React, {createContext, useContext, useState} from "react";
|
||||
|
||||
interface CounterContextProps {
|
||||
count: number,
|
||||
increment: () => void,
|
||||
decrement: () => void,
|
||||
}
|
||||
|
||||
const CounterContext = createContext<CounterContextProps | undefined>(undefined);
|
||||
|
||||
export const CounterProvider: React.FC<{children: React.ReactNode}> = ({children}) => {
|
||||
const [count, setCount] = useState(0);
|
||||
|
||||
const increment = () => setCount(count + 1);
|
||||
const decrement = () => setCount(count - 1);
|
||||
|
||||
return (
|
||||
<CounterContext.Provider value={{ count, increment, decrement }}>
|
||||
{children}
|
||||
</CounterContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useCounter = () => {
|
||||
const context = useContext(CounterContext);
|
||||
if(!context) {
|
||||
throw new Error("useContext must be used within a CounterProvider");
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user