Blog>
Snippets

Refactoring Reducers for Object.create(null)

A practical refactor example converting a traditional Redux reducer to use Object.create(null) for its initial state to prevent prototype pollution and ensure a safer state mutation.
// Traditional Redux reducer with a plain object initial state
const traditionalReducer = (state = {}, action) => {
    switch (action.type) {
        case 'ADD_ITEM':
            return {
                ...state,
                [action.payload.id]: action.payload
            };
        // ... other actions
        default:
            return state;
    }
};
This is a traditional Redux reducer where the initial state is an empty object.
// Refactored Redux reducer using Object.create(null) for initial state
const refactoredReducer = (state = Object.create(null), action) => {
    switch (action.type) {
        case 'ADD_ITEM':
            return {
                ...state,
                [action.payload.id]: action.payload
            };
        // ... other actions
        default:
            return state;
    }
};
This reducer has been refactored to use Object.create(null) to create a truly empty object without a prototype for the initial state, which can help prevent potential prototype pollution issues.