Context Management Documentation

Overview

This project uses React Context to manage global state across the application. Contexts are used to provide and consume values such as user information and theme settings. This documentation will guide you through the existing context setup and how to create your own context, including both cookie and non-cookie related contexts.

Existing Contexts

Theme Context

The ThemeContext manages the application’s theme (light or dark). It loads the theme from cookies at initialization and updates cookies when the theme changes.

ThemeContext.tsx

import { createContext, useState, useEffect, ReactNode } from 'react';
import Cookies from 'js-cookie';

type ThemeContextType = {
    theme: 'light' | 'dark';
    setTheme: (theme: 'light' | 'dark') => void;
};

export const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export const ThemeProvider = ({ children }: { children: ReactNode }) => {
    const [theme, setTheme] = useState<'light' | 'dark'>('light');

    useEffect(() => {
        const savedTheme = Cookies.get('theme') as 'light' | 'dark';
        if (savedTheme) {
            setTheme(savedTheme);
        }
    }, []);

    const updateTheme = (newTheme: 'light' | 'dark') => {
        setTheme(newTheme);
        Cookies.set('theme', newTheme, { expires: 365 });
    };

    return (
        <ThemeContext.Provider value={{ theme, setTheme: updateTheme }}>
            {children}
        </ThemeContext.Provider>
    );
};

User Context

The UserContext manages user information such as user ID and name. It does not use cookies.

UserContext.tsx

import { createContext, useState, ReactNode } from 'react';

interface User {
    id: string;
    name: string;
}

interface UserContextType {
    user: User | null;
    setUser: (user: User | null) => void;
}

export const UserContext = createContext<UserContextType | undefined>(undefined);

export const UserProvider = ({ children }: { children: ReactNode }) => {
    const [user, setUser] = useState<User | null>(null);

    return (
        <UserContext.Provider value={{ user, setUser }}>
            {children}
        </UserContext.Provider>
    );
};

Using Contexts

To use the contexts in your components, you can use the custom hooks useTheme and useUser.

ContextHooks.ts

const Component = () => {
    const { theme, setTheme } = useTheme();
    const { user, setUser } = useUser();

    return (
        <div>
            <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
                Toggle Theme
            </button>
            <p>{user ? `Hello, ${user.name}!` : 'Not logged in'}</p>
        </div>
    );
};

Creating Your Own Context