Take the below code fragment using Redux Tookit:
reducers: {
setMessage: (state, { payload }) => {
state.message = payload;
saveStore(state);
},
},
Where saveStore uses localStorage
export const saveStore = (state) => {
localStorage.setItem("store", JSON.stringify(state));
};
This works just fine. However, does this cause the reducer to no longer be pure?
My confusion is that I also think that the mutation of the disk is outside the program and as such the "no side effects" rule should not apply.
I appreciate Redux Persist is a solution, but want to see if the above breaks the way it is meant to work, and if not why?
It's not great, but it's okay - redux-persist itself works like this (conditionalUpdate here actually persists).
It's not a necessity, though - from skimming the source code, redux-remember does not do it.
Generally, it's something you'd want to avoid if possible, but the section Reducers must not have side effects mentions a "gray area" in the "Detailed Explanation" part, with an example for console.log
.
Writing to localStorage would be another (although more edge-casey) example of "in practice has no effect on how the application behaves.".