Using Object Spread Operator

Since one of the core tenets of Redux is to never mutate state, you'll often find yourself using Object.assign() to create copies of objects with new or updated values. For example, in the todoApp below Object.assign() is used to return a new state object with an updated visibilityFilter property:

  1. function todoApp(state = initialState, action) {
  2. switch (action.type) {
  3. case SET_VISIBILITY_FILTER:
  4. return Object.assign({}, state, {
  5. visibilityFilter: action.filter
  6. })
  7. default:
  8. return state
  9. }
  10. }

While effective, using Object.assign() can quickly make simple reducers difficult to read given its rather verbose syntax.

An alternative approach is to use the object spread syntax recently added to the JavaScript specification. It lets you use the spread () operator to copy enumerable properties from one object to another in a more succinct way. The object spread operator is conceptually similar to the ES6 array spread operator. We can simplify the todoApp example above by using the object spread syntax:

  1. function todoApp(state = initialState, action) {
  2. switch (action.type) {
  3. case SET_VISIBILITY_FILTER:
  4. return { ...state, visibilityFilter: action.filter }
  5. default:
  6. return state
  7. }
  8. }

The advantage of using the object spread syntax becomes more apparent when you're composing complex objects. Below getAddedIds maps an array of id values to an array of objects with values returned from getProduct and getQuantity.

  1. return getAddedIds(state.cart).map(id =>
  2. Object.assign({}, getProduct(state.products, id), {
  3. quantity: getQuantity(state.cart, id)
  4. })
  5. )

Object spread lets us simplify the above map call to:

  1. return getAddedIds(state.cart).map(id => ({
  2. ...getProduct(state.products, id),
  3. quantity: getQuantity(state.cart, id)
  4. }))

While the object spread syntax is a Stage 4 proposal for ECMAScript and accepted for the 2018 specification release, you will still need to use a transpiler such as Babel to use it in production systems. You should use the env preset, install @babel/plugin-proposal-object-rest-spread and add it individually to the plugins array in your .babelrc.

  1. {
  2. "presets": ["@babel/preset-env"],
  3. "plugins": ["@babel/plugin-proposal-object-rest-spread"]
  4. }