Html & Html5

The World's best Software Development Study Portal

Redux Store

The redux store is the object which holds the state of the application and brings them together.

A store has following responsibilities:
  • Holds application state;

  • Allows access to state via getState();

  • Allows state to be updated via dispatch(action);

  • Registers listeners via subscribe(listener);

  • It handles unregistering of listeners via the function returned by subscribe(listener)

  • Functions associated with Store:

  • createStore() – To create a store
  • dispatch(action) -To change the state
  • getState() – for getting current state of store.

  • For Example:

         	import { createStore } from 'Redux'; 
            // Creating store 
            const store = createStore(taskList); 
            // Here add is action as you can see console, 
            // its an object with some info 
            const add = addTask('Wake up'); 
           // Dispatch usually trigger reducer and preform task 
           // getState() function is used to get current state 
           store.dispatch(addTask('Go to sleep')); 

    How we can create a store using the createStore method?

    we can create a store using the createStore method from Redux. One need to import the createStore package from the Redux library that supports the store creation process as shown below −

    	import { createStore } from 'redux';
        import reducer from './reducers/reducer'
        const store = createStore(reducer); 

    A createStore function can have three arguments. The following is the syntax:

    createStore(reducer, [preloadedState], [enhancer])

    A reducer is a function that returns the next state of app. A preloadedState is an optional argument and is the initial state of your app. An enhancer is also an optional argument. It will help you enhance store with third-party capabilities.

    A store has three important methods as given below −
  • getState

  • It helps you retrieve the current state of your Redux store.
    The syntax for getState is as follows:


  • dispatch

  • It allows you to dispatch an action to change a state in your application.
    The syntax for dispatch is as follows:


  • subscribe

  • It helps you register a callback that Redux store will call when an action has been dispatched. As soon as the Redux state has been updated, the view will re-render automatically.
    The syntax for dispatch is as follows −

    store.subscribe(()=>{ console.log(store.getState());})

    Note that subscribe function returns a function for unsubscribing the listener. To unsubscribe the listener, we can use the below code −

    const unsubscribe = store.subscribe(()=>{console.log(store.getState());}); unsubscribe();