I’m working on a React application with TypeScript, and I’m using useReducer to manage a complex state structure. My state has nested objects, and I’m struggling to type the state and actions correctly. Here’s a simplified version of my setup:
type User = {
id: number;
name: string;
};
type Settings = {
theme: 'light' | 'dark';
notificationsEnabled: boolean;
};
type State = {
user: User | null;
settings: Settings;
};
type Action =
| { type: 'setUser'; payload: User }
| { type: 'clearUser' }
| { type: 'updateTheme'; payload: 'light' | 'dark' }
| { type: 'toggleNotifications' };
const initialState: State = {
user: null,
settings: {
theme: 'light',
notificationsEnabled: true,
},
};
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'setUser':
return { ...state, user: action.payload };
case 'clearUser':
return { ...state, user: null };
case 'updateTheme':
return { ...state, settings: { ...state.settings, theme: action.payload } };
case 'toggleNotifications':
return {
...state,
settings: { ...state.settings, notificationsEnabled: !state.settings.notificationsEnabled },
};
default:
throw new Error('Unknown action type');
}
}
const MyComponent: React.FC = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>User: {state.user ? state.user.name : 'No user logged in'}</p>
<p>Theme: {state.settings.theme}</p>
<p>Notifications: {state.settings.notificationsEnabled ? 'Enabled' : 'Disabled'}</p>
<button onClick={() => dispatch({ type: 'clearUser' })}>Clear User</button>
<button onClick={() => dispatch({ type: 'updateTheme', payload: 'dark' })}>Set Dark Theme</button>
<button onClick={() => dispatch({ type: 'toggleNotifications' })}>Toggle Notifications</button>
</div>
);
};
`
While this approach works, I’m having trouble with typing nested state, extending actions and of course error handling.
What are the best practices for typing nested states and actions in a React application using TypeScript? Are there patterns or utilities that can help manage complex reducers effectively?
888 crew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.