interface AppState {
user: User | null;
theme: 'light' | 'dark';
notifications: Notification[];
}
type AppAction =
| { type: 'SET_USER'; payload: User }
| { type: 'LOGOUT' }
| { type: 'TOGGLE_THEME' }
| { type: 'ADD_NOTIFICATION'; payload: Notification };
const appReducer = (state: AppState, action: AppAction): AppState => {
switch (action.type) {
case 'SET_USER':
return { ...state, user: action.payload };
case 'LOGOUT':
return { ...state, user: null };
case 'TOGGLE_THEME':
return { ...state, theme: state.theme === 'light' ? 'dark' : 'light' };
case 'ADD_NOTIFICATION':
return { ...state, notifications: [...state.notifications, action.payload] };
default:
return state;
}
};
export const AppProvider: React.FC<{children: React.ReactNode}> = ({ children }) => {
const [state, dispatch] = useReducer(appReducer, initialState);
const contextValue = useMemo(() => ({
state,
dispatch,
actions: {
login: (user: User) => dispatch({ type: 'SET_USER', payload: user }),
logout: () => dispatch({ type: 'LOGOUT' }),
toggleTheme: () => dispatch({ type: 'TOGGLE_THEME' }),
addNotification: (notification: Notification) =>
dispatch({ type: 'ADD_NOTIFICATION', payload: notification }),
},
}), [state]);
return <AppContext.Provider value={contextValue}>{children}</AppContext.Provider>;
};