InterviewHubPRO
Section Overview
Q110

Question 110 of 445

Part 5: React Redux State Management (101 - 134)

25%
React & Modern Frontend (445 Qs)•Part 5: React Redux State Management (101 - 134)

How to reset state in Redux?

You need to write a root reducer in your application which delegate handling the action to the reducer generated by combineReducers().

For example, let us take rootReducer() to return the initial state after USER_LOGOUT action. As we know, reducers are supposed to return the initial state when they are called with undefined as the first argument, no matter the action.

javascript
const appReducer = combineReducers({
/* your app's top-level reducers */
});

const rootReducer = (state, action) => {
if (action.type === "USER_LOGOUT") {
  state = undefined;
}

return appReducer(state, action);
};

In case of using redux-persist, you may also need to clean your storage. redux-persist keeps a copy of your state in a storage engine. First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and clean each storage state key.

javascript
const appReducer = combineReducers({
/* your app's top-level reducers */
});

const rootReducer = (state, action) => {
if (action.type === "USER_LOGOUT") {
  Object.keys(state).forEach((key) => {
    storage.removeItem(`persist:${key}`);
  });

  state = undefined;
}

return appReducer(state, action);
};