Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Advanced

Logout Patterns

Definition

The architectural requirement to completely wipe out all sensitive data from the Redux store when a user logs out, preventing the next user on the same computer from seeing it.

Explain Like I'm New

If John logs in, Redux fetches his credit card history. If John clicks 'Logout', the `auth.isLoggedIn` changes to false. BUT, the credit card history is still sitting inside `state.billing`. If Jane logs in on the same laptop 5 minutes later, the billing slice hasn't been cleared, and Jane sees John's credit cards. You must destroy the entire state on logout.

Real World Example

Writing a Root Reducer interceptor that listens for the `USER_LOGOUT` action and replaces the entire Redux state tree with `undefined`.

Common Use Cases

  • •Security
  • •Data privacy in shared environments

Interactive Example

import { combineReducers, configureStore } from '@reduxjs/toolkit';
import authReducer from './authSlice';
import billingReducer from './billingSlice';

const appReducer = combineReducers({
  auth: authReducer,
  billing: billingReducer,
});

// The Root Reducer Interceptor!
const rootReducer = (state, action) => {
  // If the user clicks logout...
  if (action.type === 'auth/logout') {
    // Passing 'undefined' to appReducer forces EVERY slice 
    // to reset back to its initialState!
    state = undefined;
  }

  return appReducer(state, action);
};

export const store = configureStore({
  reducer: rootReducer,
});

Interview Questions

basic

  • Should you write a `logout` reducer in every single slice (auth, billing, profile) to clear their data individually?

intermediate

  • How do you clear the entire RTK Query cache on logout?

Flash Cards

Question

Clear individually?

Click to reveal answer
Answer

No. That is error-prone. If you add a new slice and forget to handle the logout action, data will leak. It is better to clear the entire Root Reducer at once.

Question

Clear RTK Query cache?

Click to reveal answer
Answer

Dispatch `api.util.resetApiState()`. It instantly destroys all cached data from all endpoints.