redux

Getting started with redux

Remarks#

Redux is a JavaScript library that implements state container of the Flux-based architecture.

Redux can be described in three fundamental principles:

  1. Single source of truth (Single store)
  2. State is read only (need actions to signal change)
  3. Changes are made with pure functions (This creates new state according to the actions)

Main parts:

  • store constructor
  • store.dispatch(action)
  • middleware
  • reducers

Redux is astonishingly simple. It uses a function called a reducer (a name derived from the JavaScript reduce method) that takes two parameters: An action, and a next state.

The reducer has access to the current (soon to be previous) state, applies the given action to that state, and returns the desired next state.

Reducers are designed to be pure functions; meaning, they produce no side effects. If you pass the same input values to a reducer 100 times, you will get the exact same output value 100 times. Nothing weird happens. They are completely predictable. As someone with a prominent “NO SURPRISES” sticky note on my monitor, this is a wonderful idea to contemplate.

Reducers do not store state, and they do NOT mutate state. They are passed state, and they return state. This is what reducers look like in action. https://redux.js.org/docs/basics/Reducers.html

Reference: https://redux.js.org/docs/introduction/Motivation.html

Versions#

VersionsRelease Date
v3.6.02016-09-04
v3.5.02016-04-20
v3.4.02016-04-09
v3.3.02016-02-06
v3.2.02016-02-01
v3.1.02016-01-28
v3.0.02015-09-13
v2.0.02015-09-01
v1.0.02015-08-14

Installation or Setup

Basic installation:

You can download redux javascript file, using this link.

Also you can install redux, using bower :

bower install https://npmcdn.com/redux@latest/dist/redux.min.js

Next, you need to include redux to your page:

<html>
  <head>
    <script type="text/javascript" src="/path/to/redux.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script>
      // Redux is available as `window.Redux` variable.
    </script>
  </body>
</html>

Npm installation:

If you are using npm, to install redux, you need to run:

npm install redux --save

Next, to use redux, you need to require it (assuming you are using module bundler, like webpack):

var redux = require('redux');

Or if you are using es6 transpiler, like babel:

import redux from 'redux';

Vanilla Redux Example (without React or others)

You can see the running demo by clicking here.

HTML:

<p>
  <span>Counter State</span><br />
  (<em>Will increase each minute</em>):
  <p>
    <span id="counter-state" style="font-weight: bolder"></span>
  </p>
</p>

<p>
  <button id="increment-action">+ Increase +</button>
  <button id="decrement-action">- Decrease -</button>
</p>

REDUX LOGIC:

// ------------------------ reducer helpers ------------------------
let reducers = {}

let addReducer = (reducers, actionType, reducer) =>
  reducers[actionType] = (state, action) => {
    if (action.type == actionType) {
      return reducer(state, action)
    }
  }

let reducer = (state, action) => {
  if (reducers[action.type]) {
    return reducers[action.type](state, action)
  }
  return state
}


// ------------------------ redux setup ------------------------

const { 
  createStore,
  applyMiddleware
  } = Redux


// apply logging middleware (not necessary)
// open the console to see the action logger output on each time new action dispatched
const actionLogger = ({ dispatch, getState }) => next => action => {
  console.log("action logger: action.type=%s state=%d", action.type, getState())
  return next(action)
}


// ------------------------ reducers ------------------------
// those will be creating new states and returning it,
// depending on the dispatched actions
addReducer(reducers, 'INCREMENT', (state, action) => ++state)
addReducer(reducers, 'DECREMENT', (state, action) => --state)


const DEFAULT_STATE = 0

const store = createStore(
  reducer, 
  DEFAULT_STATE, 
  applyMiddleware(actionLogger)
);


console.log(createStore)


// ------------------------ rendering ------------------------
let render = () => document.getElementById('counter-state').innerHTML = store.getState()

//
// IMPORTANT BINDING:
//
// store will be dispatching the new state to the render method each time the state changes
//
store.subscribe(render)

//
// render with the state for the first time
//
render()



// ------------------------ redux actions ------------------------

// continously increment the counter (the state) each second
setInterval(() => store.dispatch({type: 'INCREMENT'}), 1000)

// only increment the counter on click to the increase button
document
  .getElementById('increment-action')
  .addEventListener('click', () => store.dispatch({type: 'INCREMENT'}))

// only decrement the counter on click to the decrease button
document
  .getElementById('decrement-action')
  .addEventListener('click', () => store.dispatch({type: 'DECREMENT'}))

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow