-
-
Save tobySolutions/9664f5be6a1c27368c232187bb698958 to your computer and use it in GitHub Desktop.
Context stuff
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 { createContext, useContext, ReactNode, useState } from 'react'; | |
// Define the type for user information | |
interface User { | |
id: number; | |
username: string; | |
} | |
// Define the type for the context | |
interface AppContextProps { | |
darkMode: string | null; | |
setDarkMode: React.Dispatch<React.SetStateAction<string | null>>; | |
user: User | null; | |
setUser: React.Dispatch<React.SetStateAction<User | null>>; | |
} | |
// Create the context | |
const AppContext = createContext<AppContextProps | undefined>(undefined); | |
// Create a provider component | |
export function AppProvider({ children }: { children: ReactNode }) { | |
const [darkMode, setDarkMode] = useState<string | null>(null); | |
const [user, setUser] = useState<User | null>(null); | |
return ( | |
<AppContext.Provider value={{ darkMode, setDarkMode, user, setUser }}> | |
{children} | |
</AppContext.Provider> | |
); | |
} | |
// Custom hook to access the app context | |
export function useApp() { | |
const context = useContext(AppContext); | |
if (!context) { | |
throw new Error('useApp must be used within an AppProvider'); | |
} | |
return context; | |
} | |
const { darkMode, setDarkMode, user, setUser } = useApp(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment