Skip to content

Instantly share code, notes, and snippets.

@tobySolutions
Last active December 16, 2023 16:46
Show Gist options
  • Save tobySolutions/9664f5be6a1c27368c232187bb698958 to your computer and use it in GitHub Desktop.
Save tobySolutions/9664f5be6a1c27368c232187bb698958 to your computer and use it in GitHub Desktop.
Context stuff
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