36

I searched a bit about this question but found very vague answers. In redux, we know that the state is stored as an object. But where is this state stored actually? Is it somehow saved as a file which can be accessed by us later on? What I know is that it does not store it in a cookie format or in the browser's local storage.

nem035
  • 34,790
  • 6
  • 87
  • 99
Dhruv Marwha
  • 1,064
  • 2
  • 14
  • 26

2 Answers2

51

The state in Redux is stored in memory, in the Redux store.

This means that, if you refresh the page, that state gets wiped out.

You can imagine that store looking something like this:

function createStore(reducer, initialState) {
  let state = initialState // <-- state is just stored in a variable that lives in memory

  function getState() {
    return state
  }

  function dispatch(action) {

    state = reducer(state, action) // <-- state gets updated using the returned value from the reducer

    return action
  }

  return {
    getState,
    dispatch
  }
}

The state in redux is just a variable that persists in memory because it is referenced (via closure) by all redux functions.

Here's a simplified example of what is going on:

function example() {
  let variableAvailableViaClosure = 0
  
  function incrementTheClosureVariable() {
    variableAvailableViaClosure += 1
  }

  function getTheClosureVariable() {
    return variableAvailableViaClosure
  }

  return {
    incrementTheClosureVariable,
    getTheClosureVariable
  }
}

let data = example()

// at this point example is finished
// but the functions it returned
// still have access to the (internal) variable via closure

console.log(
  data.getTheClosureVariable() // 0
)

data.incrementTheClosureVariable()

console.log(
  data.getTheClosureVariable() // 1
)

Furthermore, the statement

In redux, we know that the state is stored as an object.

isn't correct. State in redux can be any valid javascript value, not just an object. It just usually makes the most sense for it to be an object (or a special object like an array) because that allows for a more flexible data structure (but you could make the state just be a number for example, if you wanted to).

Check out the actual Redux implementation for more details.

If you want the state to persist in a cookie or localStorage, you would enhance the store such that, on top of updating the state in memory, it will save to your desired storage as well (and load from that storage when the store is initialized)

nem035
  • 34,790
  • 6
  • 87
  • 99
  • 2
    memory? is it RAM memory? – G_S Mar 05 '18 at 06:02
  • 6
    Yes. In the RAM – nem035 Mar 05 '18 at 06:03
  • Trying to figure out the line where they are doing it. Can you help me out to find it? – G_S Mar 05 '18 at 06:04
  • If that is the case,then exactly what would be the use of a state.I can just normally pass variables between components. – Dhruv Marwha Mar 05 '18 at 06:10
  • 3
    The point of state is that is is enclosed from the rest of the world (checkout the [Module Pattern](https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript)) and only alterable using a strict API exposed via pure functions (the action dispatchers). This means that state is localized and manipulated without side-effects. If you just passed data around to all components then any component, at any time, can change that state which creates problems that are hard to debug and code that is difficult to reason about (the state changes can happen anywhere at any time). – nem035 Mar 05 '18 at 06:12
  • 1
    @JamesBarrett looks like the Redux codebase got converted to TypeScript and it broke all my links (that were pointing to `.js` files). Should be updated now. – nem035 Sep 10 '19 at 13:41
-5

States are stored in redux-store. Redux Store is a global store which can be accessed anywhere/any components.

Let consider an example of getting Index of data using third party API. The following snippet uses componentWillMount which will trigger a fetch call using redux action.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchDataFromUrl } from '../actions/index.js';


class Indexdata extends Component {


  constructor(props){
    super(props);
    this.state = {
      text: ''
    }
  }


  componentWillMount(){
    let thisVal = this;
      thisVal.props.fetchIndexofData()
  }

  componentWillReceiveProps(nextProps){
    this.setstate({
      text: nextProps.indexData.text
    })
  }

  render(){
    return(
      <div>
        <Navbar />
        <h2 className="prescription-index-title">Index of Data</h2>
      </div>
    )
  }
}

function mapStateToProps(state){
  return{
    indexData: state.fetchedData
  }
}

function mapDisptachToProps(dispatch){
  return {
    fetchIndexofData: () => dispatch(fetchDataFromUrl(access_token))
  };
};

export default connect(mapStateToProps, mapDisptachToProps)(IndexData);

The above snippet will fetch index of data using a redux action. The below code is a redux action,

export function fetchDataFromUrl(){
  return(dispatch) => {
    const base_url = "https://api_serving_url.com"
    fetch(base_url, {
      method: 'GET'
    })
    .then(response => response.json())
    .then(data => {
      dispatch({
        type: "INDEX_DATA",
        data: data
      })
    })
  }
}

Redux action will dispatch data to reducer, where state will be initialized in redux store. The following code snippet is redux-reducer

export function fetchedData(state = [], action) {
  switch(action.type) {
    case "INDEX_DATA":
      return action.data;
    default:
      return state; 
  }
}

State stored in redux store will be mapped using function mapStateToProps, implemented in the above component. Now you can access the state using props in the respective component. Lifecyclehook componentWillReceiveProps will be able to fetch the state stored redux store.

You can access the State by means of using store.getState() in any component.The only drawback of using reducer state, is that it will reset the state when you refresh the component/application. Go through Reducer Store , for more information.

Thananjaya S
  • 1,451
  • 4
  • 18
  • 31
  • 7
    So now, state is stored in redux store. and where redux store is stored? – G_S Mar 05 '18 at 06:31
  • Redux store is stored in your browser storage. That's why on refreshing your page, eventually that re-renders your component which make your redux-store to reset. – Thananjaya S Mar 05 '18 at 06:37
  • 5
    No @ThananjayaChakravarthy, It get store in RAM. if you don't want to swipe, you can use redux-persist https://github.com/rt2zz/redux-persist. – S.Yadav Nov 28 '18 at 06:27