DEV Community

Discussion on: How To Setup Redux with Redux Toolkit

Collapse
 
markerikson profile image
Mark Erikson • Edited

Hi, I'm a Redux maintainer. Always glad to see new tutorials showcasing Redux Toolkit!

I do see one small issue I want to point out. In this snippet, localStorage.setItem() is technically a side effect:

const slice = createSlice({
  name: 'user',
  initialState: {
-    user: null,
+    user: initialUser,
  },
  reducers: {
    loginSuccess: (state, action) => {
      state.user = action.payload;
+      localStorage.setItem('user', JSON.stringify(action.payload))
    },
    logoutSuccess: (state, action) =>  {
      state.user = null;
+      localStorage.removeItem('user')
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

The code will run, but that's not what a reducer is supposed to be doing.

Persistence logic like that should really be not be in a reducer - it should be at the store setup level, or possibly at the UI level. In this case, it could be done with a simple store.subscribe() call, in a middleware, or similar.