Redux Store

redux store

    Redux Store is a single javascript object that includes our application state. The current Redux application state lives in an object called the store.

    To create a store we need to import createStore function from redux.

import { createStore } from 'redux';

    Now,we need to pass the reducer to createStore,

 import reducer from './reduer';
 createStore(reducer); 

    we need to pass the reference of reducer to createStore. CreateStore is a higher-order function that takes a function reference as an argument.

    The final code for creating store is as follows:

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

What actually store object has?

import React from 'react'
import store from './store';
function App() {
    console.log("store>>>",store);
    return (
        <div>
            Redux Store
        </div>
    )
}

export default App

     Output of above code will look like,

the store has below properties:

 1.getState - Allows access to the current state
 2.dispatch - Allows state to be updated
 3.subscribe - Registers listener callbacks 
 4.replaceReducer
 5.Symbol(Observable) 

1.geState():

In redux to access the state of the store, we are available with the getState() method.

Syntax: Store.getState();

well, we only have getState() not the setState, this is the fundamental principle in redux.

To change the state of the store we have to dispatch the action. With this architecture we are essentially sending every action through the same entry point i.e dispatch this is the beauty of redux.

To check the state of store use

console.log(store.getState());

import {createStore} from 'redux';
const init={
    user:[]
}
function reducer(state=init,action){
return state;
}
const store= createStore(reducer);

export default store;
import React from 'react'
import store from './store';
function App() {
    console.log("store.getState>>>",store.getState());
    return (
        <div>
            Redux Store
        </div>
    )
}

export default App

Output will be,

2.dispatch():

    The redux store has a method called dispatch.this method is the only way to update the state of redux store.We call dispatch method and pass a action object as shown below.

store.dispatch({
        type:'USER_ADDED',
        payload:{
            id:1,
            name:'webdev99'
        }
 });
import {createStore} from 'redux';
const init={
    user:[]
}
function reducer(state=init,action){
    
    if(action.type === 'USER_ADDED'){
        
        return {
            ...state,
            user:[...state.user,{id:action.payload.id,
                  name:action.payload.name}
                 ]
        }
    }
    else
        return state;

}
const store= createStore(reducer);

store.subscribe(()=>{
   console.log("store",store.getState());
});
export default store;

    Console Output Will look like,

store {user: Array(1)}
         user: Array(1) 
                 {0: id: 1, name: "webdev99"}
         proto: Objectlength: 1__proto__: Array(0)
         proto: Object

3.Subscribe():

    subscribe is a function that gets called every time when the state of the store gets change.UI components should subscribe to the store so that they get notified when the state of the store changes.

store.subscribe(()=>{
 console.log("store changed!!!",store.getState());
 }); 

use of subscribe:

    If your building your application with vanilla js or jquery then this is the place where we are gonna work with DOM elements to refresh the view. If you are building the application with react then we will re-render.

unsubscribe:

1.this subscribe function returns a function for unsubscribing from the store.
2.subscription creates a memory leak when the user gets navigated to other parts of UI where he/she doesn’t use the store subscription.

    Hence need to unsubscribe the store.

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

 unsubscribe();

    If we unsubscribe the store then we dont get notified by store.subscribe.

Bonus:

Loading Initial State for Store:

    createStore can accept a initialstate value as its second argument. You could use this to add initial data when the store is created, such as values that were included in an HTML page sent from the server, or persisted in localStorage and read back when the user visits the page again.

let initialState;
const userString = localStorage.getItem('user')

if (userString) {
  initialState = {
    user: JSON.parse(userString)
  }
}

const store= createStore(reducer,initialState);

store.subscribe(()=>{
   console.log("store",store.getState());
});
export default store;

for doubts use below comment box,

Thanks for reading the article… 🙂

Leave a Reply