Multiple Reducers for Separation of Concerns
Split complex state logic into multiple reducers to handle distinct areas of state, and then combine them using useReducer for organized state management.
// Reducer for handling user state
const userReducer = (state, action) => {
switch (action.type) {
case 'SET_USER':
return {
...state,
user: action.payload
};
default:
return state;
}
};
This is a reducer for managing the user portion of the state, such as user details or authentication status.
// Reducer for handling theme state
const themeReducer = (state, action) => {
switch (action.type) {
case 'SET_THEME':
return {
...state,
theme: action.payload
};
default:
return state;
}
};
This is a reducer dedicated to handling the theme portion of the state, such as theme colors or dark mode settings.
// Reducer to combine all the separate reducers
const mainReducer = ({ user, theme }, action) => (
{
user: userReducer(user, action),
theme: themeReducer(theme, action)
}
);
This is a main reducer that combines the userReducer and themeReducer, so they can be used together in a single useReducer hook in a React component.
// Usage of the combined reducers with React's useReducer hook
const initialState = {
user: null,
theme: 'light'
};
const [state, dispatch] = React.useReducer(mainReducer, initialState);
This shows how to initialize and make use of the combined reducers within a React component by using the useReducer hook.