Redux in JavaScript

(Redux is a JavaScript library for managing and centralizing application state.)

Basic


Syntaxes

createStore()

Syntax:
const store = createStore( reducerFunction_as_callback , preloadedState?, enhancer? )

reducerFunction

Reducer take in two things as parameter: i) previous state ii) and an action.

Syntax:
( state , action ) => newState

STORE METHODS

getState()

Syntax:
store .getState()

dispatch(action)

Dispatches an action to the Redux store. The store runs the reducer function again with the previous state and the current action. Note: This is the only way to trigger a state change.

Syntax:
store .dispatch( action )

subscribe( listenerFunction_callback )

subscribe() registers a function to be called on state changes Note: You may then call getState() to read the current state tree inside the callback.

Syntax:
store .subscribe( listenerFunction_callback )

unsubscribe()

To unsubscribe the change listener, invoke the function returned by subscribe.

Syntax:
const unsubscribe = store .subscribe( listenerFunction_callback ) unsubscribe()

Example 1

Run output in terminal node filename.js

Terminal

{ value: 1 }
{ value: 2 }
{ value: 1 }

Live output

STEPS:

  • Create a Store,
    1. Create Reducer Function inside createStore() call,
      1. Put state object inside Reducer Function call,
      2. Pass an action object inside Reducer Function call,
      3. Put state updating code inside Reducer Function block and return the new state.
    2. Dispatch an action object to the Store. (The store runs the reducer function).
    3. Subscribe a function to be called whenever the state changes.
    4. Get the current state using getState()
// import { createStore } from "redux";
  const redux = require('redux'); 
  
  function counterReducer(state = { value: 0 }, action) {
    switch (action.type) {
      case "counter/incremented":
        return { ...state, value: state.value + 1 };
  
      case "counter/decremented":
        return { ...state, value: state.value - 1 };
  
      default:
        return state;
    }
  }
  
  // Create a Redux store holding the state of your app.
  // Its API is { subscribe, dispatch, getState }.
  let store = redux.createStore(counterReducer);
  
  // You can use subscribe() to update the UI in response to state changes.
  // Normally you'd use a view binding library (e.g. React Redux) rather than 
  // subscribe() directly.
  // There may be additional use cases where it's helpful to subscribe as well.
  // store.subscribe(() => console.log(store.getState()));
  
  // The only way to mutate the internal state is to dispatch an action.
  // The actions can be serialized, logged or stored and later replayed.
  store.dispatch({ type: "counter/incremented" }); //{value: 1}
  
  store.dispatch({ type: "counter/incremented" }); //{value: 2}
  
  store.dispatch({ type: "counter/decremented" }); //{value: 1}  

Example 2

JS with full HTML code

Click for Live Preview link

<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plain JavaScript Redux Example</title>
    <style>
      button{
        padding:10px;font-size:16px;margin:10px;color:#FFF;
        font-weight:bold;cursor:pointer
      }
      #increment{background:#1a524d}
      #decrement{background:#7a2c46}
    </style>
  </head>
  <body>
  
  <button id="increment">dispatch an action object type "INCREMENT"</button>
  <button id="decrement">dispatch an action object type "DECREMENT"</button>
  
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.1.1/redux.min.js"></script>
  
  <script>
  
const { createStore } = Redux; // Alternate to import createStore
  
    // Creating State object
    const initialState = {
      count: 0,
    };
  
    // REDUCER FUNCTION - takes previous state and an action. 
    // And "RETURNS A NEW STATE".
    // ( state , action ) => newState
    function rootReducerFn( state = initialState, action ) {
      switch (action.type) {
        case 'INCREMENT':
          return { ...state, count: state.count + 1 };
        case 'DECREMENT':action
          return { ...state, count: state.count - 1 };
        default:
          return state;
      }
    }
  
    // Creating a store ######################
    const store = createStore( rootReducerFn );
    // #######################################
  
  
    // Redux store subscribe
    // subscribe() registers a function to be called on state changes
    store.subscribe(() => {
      console.log('Current State:', store.getState());
    });
  
  
    // JS EventListener Start -----------------
    document.getElementById('increment')
      .addEventListener('click', function () {
        // Dispatching an action
        store.dispatch( {type: 'INCREMENT'});      
        // Put the action object inside dispatch() call
      });
  
    document.getElementById('decrement')
      .addEventListener('click', function () {
        // Dispatch the action
        store.dispatch( decrement() ) 
        //We can also put the action type object in a function and call it. 
      })
    // JS EventListener End ---------------------
  
    function decrement() {
      return { type: 'DECREMENT' }; // action type object
    }

    </script>
  </body>
  </html>