Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  129] [ 7]  / answers: 1 / hits: 18911  / 6 Years ago, mon, march 5, 2018, 12:00:00

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.


More From » reactjs

 Answers
5

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)


[#55017] Wednesday, February 28, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
martina

Total Points: 101
Total Questions: 103
Total Answers: 111

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;