× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Tip on writing effective reducer code for Redux.

Vijay Thirugnanam
Oct 10, 2016
<p>The reducer in Redux is the place where code is written to mutate the state in the store. Every reducer is given the previous state of the reducer in the store and a new action. The reducer decides whether to mutate the store for a given action. Example redux code is shown below.</p> <pre><code class="language-javascript">function myReducer(state = {}, action) { switch(action.type) { case 'MY_ACTION': return Object.assign({}, state, { prop1: 'prop value' }); case default: return state; } }</code></pre> <p>The above code works well for a simple state. But when the state contains arrays and nested objects, care should be taken not to mutate the object in the previous state. If the object in the previous state is mutated, then there is no difference between the objects in the previous and next state. So, React components won't render the diff in the virtual DOM. </p> <p>To ensure that we are mutating objects in the next state and not the previous state, we should slice an array and shallow copy an object.</p> <p>If the state contains an array, before pushing or splicing an array, we should make a copy of the array as follows.</p> <pre><code>newState.array = state.array.slice(); newState.array.push(obj); // or to remove. newState.array.splice(removeIndex, 1);</code></pre> <p>For nested objects, we should shallow copy the object that is mutated.</p> <pre><code>newState.nestedObject = Object.assign({}, state.nestedObject, { prop1: 'prop val' });</code></pre> <p>It might be tempting to do a deep clone of the entire state before mutating. But that is a bad practice. Deep clone of the entire state will cause React component to re-render the entire page. For example, if you have a search page with 20 objects, when an action is triggered to update a single object, a deep copy will mutate all the objects and re-render the 20 objects instead of the one object. Performance of the React app will be poor.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus