You may have heard that Redux depends on “pure functions” from functional programming. Well, what exactly does that mean?

The picture below shows a simple Todo app from Redux examples. It currently has four tasks. It shows the fourth one as completed, and is set to show “All” Tasks — both completed and not completed.

The right-hand side shows the current state stored in Redux. It’s a simple JavaScript object that captures all the details in one place.

That’s the beauty of Redux.

LEFT: Todo app ← →RIGHT: Redux stated

Now, let’s say you toggled the fourth task to be not-completed. Here’s what the app would look like with a new Redux state:

Redux updates it’s state when the app changes

Now, if you look at the Reducer for “TOGGLE_TODO” — the one that toggles the status of a Todo item between completed and not completed — it looks like below (here’s the source code):

When you toggle a Todo item’s state, this is what happens: the reducer function takes an object that represents the “old” state (i.e. input to a function), then creates a brand new object by copying all the old object’s details into a it (like id and text) and overriding old properties with new ones (completed prop).

Pure functions

At a fundamental level, any function that doesn’t alter input data and that doesn’t depend on external state (like a database, DOM, or global variable) and consistently provides the same output for the same input is a “pure” function.

For example, the below add function doesn’t alter “a” or “b”, doesn’t depending on external state, and always returns the same output for the same input.

const add = (a, b) => a + b //pure function

Now, if you look at our reducer function, it is a “pure” function as it has the same features.

But why should the reducer be a “pure” function?

Let’s see what happens if we make our reducer “impure.” Let’s comment out the section where it creates a new object, and instead let’s mutate the state’s completed prop directly.

case 'TOGGLE_TODO':

if (state.id !== action.id) {

return state;

}

// return {

// ...state,

// completed: !state.completed

// } state.completed = !state.completed;//change original object

return state; default: ...

Now if we try to toggle the TODO after this change, nothing happens!

Let’s see what’s going on in the Redux’s source.