Redux example

Of what exists Redux?

What is in a store?

The store contains the history of immutable state changes. Every action that is executed leads to another addition to the store.

Imutable means that these changes are stored as it is and can't be changed. When you want a state change, you make a copy of the last state with its mutation.

import { applyMiddleware, createStore } from 'redux';

export function configureStore(reducers, initialState = {}) {

    const store = createStore(

    return store;

What is an action?

An action functiones as the communicator (or glue) between a reducer and a store. When you want to change a state you execute (dispatch) an action. That is nothing else then firing a trigger that contains the action with a type (like: 'ADD-PRODUCT-TO-SHOPPING-CARD') and an object that contains the object with the state as you would like to save it in the store as the new state.
That is all an action does. It doesn't change the state by itself.

export const lightSwitched = (name) => ({
    whoPressedIt: name

What is a reducer?

The reducer is the only one that can modify the contents of a store. State changes are copies of the former state, with the mutations saved in the new state. This is done by merging the state objects in a new object.

export const SomeReducer = (state = {}, action) => {
    let newState = state;

    const initState = {
        time: someTime,
        lightIsOn: false,
        whoPressedIt: null

    switch (action.type) {
        case '@@INIT':
            newState = initState;

        case 'LIGHT_SWITCH_PRESSED':
            let lightIsOn = state.lightIsOn ? false : true;
            newState = Object.assign({}, state, {
                   time: someOtherTime,
                   lightIsOn: lightIsOn,

    return newState;
Last update: Fri, 01 Jun 2018 19:06:57