Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  75] [ 3]  / answers: 1 / hits: 137131  / 8 Years ago, wed, february 10, 2016, 12:00:00

I want to persist some parts of my state tree to the localStorage. What is the appropriate place to do so? Reducer or action?


More From » redux

 Answers
18

Reducer is never an appropriate place to do this because reducers should be pure and have no side effects.



I would recommend just doing it in a subscriber:



store.subscribe(() => {
// persist your state
})


Before creating the store, read those persisted parts:



const persistedState = // ...
const store = createStore(reducer, persistedState)


If you use combineReducers() you’ll notice that reducers that haven’t received the state will “boot up” as normal using their default state argument value. This can be pretty handy.



It is advisable that you debounce your subscriber so you don’t write to localStorage too fast, or you’ll have performance problems.



Finally, you can create a middleware that encapsulates that as an alternative, but I’d start with a subscriber because it’s a simpler solution and does the job well.


[#63369] Monday, February 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;