O'Reilly logo

React Native By Example by Richard Kho

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Building reducers

Let's look at how we would build reducers to handle creating a new task and saving it into our list of tasks.

Assuming we're working with the following state tree:

{ 
  tasks: [ 
    { 
      title: 'Buy Milk', 
      completed: false, 
      dueDate: undefined 
    }, 
    { 
      title: 'Walk Dog', 
      completed: true, 
      dueDate: undefined 
    } 
  ], 
} 

In the interest of writing a pure function, we want to make sure that we're not mutating the state and instead re-assigning our state to contain the updated changes.

In an impure function, we would simply do something like this:

Don't do this!
function addTask (state, action) { 
  switch(action.type) { 
    case 'ADD_TASK': 
      state.tasks.push({ 
        title: action.title, 
        completed: false 
      }); 
      return state; 
    default: 
      return state; 
  } 
}; 

What ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required