Migrating from Object Literals to Object.create(null) in Redux
Provide an example of refactoring existing Redux code by replacing object literals with Object.create(null) for state initialization.
// Redux Reducer using object literal for initial state
const initialState = {
counter: 0
};
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return {
...state,
counter: state.counter + 1
};
case 'DECREMENT':
return {
...state,
counter: state.counter - 1
};
default:
return state;
}
}
Initial Redux counter reducer using object literal for initial state.
// Refactored Redux Reducer using Object.create(null)
const initialState = Object.create(null);
initialState.counter = 0;
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return Object.assign(Object.create(null), state, { counter: state.counter + 1 });
case 'DECREMENT':
return Object.assign(Object.create(null), state, { counter: state.counter - 1 });
default:
return state;
}
}
Refactored Redux counter reducer using Object.create(null) for initial state to avoid the prototype chain.
/* HTML */
<div id='app'>
<button id='increment'>Increment</button>
<button id='decrement'>Decrement</button>
<div>Counter: <span id='counterValue'>0</span></div>
</div>
HTML structure for the counter application.
/* CSS */
#app {
text-align: center;
}
#counterValue {
font-weight: bold;
}
button {
margin: 5px;
padding: 10px 15px;
}
CSS styles for the counter application.
/* JavaScript - Redux Store Setup and Event Listeners */
const { createStore } = Redux;
const store = createStore(counterReducer);
const incrementButton = document.getElementById('increment');
const decrementButton = document.getElementById('decrement');
const counterDisplay = document.getElementById('counterValue');
incrementButton.addEventListener('click', () => {
store.dispatch({ type: 'INCREMENT' });
});
decrementButton.addEventListener('click', () => {
store.dispatch({ type: 'DECREMENT' });
});
store.subscribe(() => {
const state = store.getState();
counterDisplay.textContent = state.counter;
});
JavaScript code setting up the Redux store and DOM event listeners for increment and decrement actions.