Last active
September 22, 2023 20:53
-
-
Save renaco/87ac267ab5cd413e5d3836ef7fb12876 to your computer and use it in GitHub Desktop.
MyContextProvider by AI
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, { createContext, useContext, useMemo } from "react"; | |
interface MyContextProps { | |
param1: string; | |
param2: number; | |
children: React.ReactNode; // Add children property to the interface | |
} | |
const MyContext = createContext<MyContextProps | undefined>(undefined); | |
const MyContextProvider: React.FC<MyContextProps> = ({ | |
param1, | |
param2, | |
children, // Add children to the destructured props | |
}) => ( | |
<MyContext.Provider | |
value={useMemo( | |
() => ({ param1, param2, children }), | |
[param1, param2, children] | |
)} | |
> | |
{children} | |
</MyContext.Provider> | |
); | |
const useMyContext = () => { | |
const context = useContext(MyContext); | |
if (!context) { | |
throw new Error("useMyContext must be used within a MyContextProvider"); | |
} | |
return context; | |
}; | |
export { MyContextProvider, useMyContext }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment