Blog>
Snippets

Reducer Composition with ES6 Spread Operator

Demonstrate how to use the ES6 spread operator to concisely combine state slices in reducers without mutating the original state object.
// Initial state of the app
const initialState = {
    user: null,
    tasks: [],
    filter: 'all'
};

// Example of action object
const action = { type: 'ADD_TASK', task: { id: 1, text: 'Learn Reducers', completed: false } };

// User reducer
function userReducer(state = initialState.user, action) {
    switch (action.type) {
        // handle actions related to the user here
        default:
            return state;
    }
}

// Tasks reducer
function tasksReducer(state = initialState.tasks, action) {
    switch (action.type) {
        case 'ADD_TASK':
            // Use the spread operator to add a new task
            return [...state, action.task];
        // handle other actions related to tasks here
        default:
            return state;
    }
}

// Filter reducer
function filterReducer(state = initialState.filter, action) {
    switch (action.type) {
        // handle actions related to filter here
        default:
            return state;
    }
}

// Root reducer composition using spread operator
function rootReducer(state = initialState, action) {
    return {
        user: userReducer(state.user, action),
        tasks: tasksReducer(state.tasks, action),
        filter: filterReducer(state.filter, action)
    };
}
This code defines a root reducer composed of smaller reducers each handling a specific slice of the state (user, tasks, filter). The rootReducer function combines different slices of the state into a new state object without mutating the original state object, using the spread operator to merge changes as needed.