Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Advanced

Dynamic Reducers

Definition

The architectural pattern of injecting new reducers into the Redux store AFTER the application has already started running, rather than defining all reducers upfront in `configureStore`.

Explain Like I'm New

If you have a massive app with 50 features, loading all 50 Reducers on the initial page load will make your website incredibly slow. Dynamic reducers allow you to load the 'Checkout' reducer ONLY when the user actually navigates to the Checkout page.

Real World Example

A Micro-frontend architecture. The core shell app loads. When the user clicks the 'Support Chat' widget, the browser downloads the Chat JavaScript, and dynamically injects the `chatReducer` into the running Redux store.

Common Use Cases

  • •Code splitting
  • •Micro-frontends
  • •Massive enterprise applications

Terminal Output

bash / terminal
/* Conceptual flow of Code Splitting Reducers: 1. App starts. configureStore() runs with ONLY the core reducers (auth, ui). 2. User clicks 'Dashboard'. 3. React Lazy loads the Dashboard.jsx component. 4. Inside Dashboard.jsx, a useEffect runs: `store.injectReducer('dashboard', dashboardSlice.reducer)` 5. The Redux store recalculates its state tree. 6. The Dashboard component can now use `useSelector(state => state.dashboard)`. */

Interview Questions

basic

  • What Redux store method is used to swap out or inject reducers at runtime?

intermediate

  • If a dynamically injected slice dispatches an action BEFORE it is injected, what happens?

Flash Cards

Question

Which method?

Click to reveal answer
Answer

`store.replaceReducer()`

Question

Dispatched before injection?

Click to reveal answer
Answer

The action will fire, but because the specific reducer hasn't been injected yet, the action will hit the `default` switch cases of the existing reducers and do absolutely nothing. The data will be lost.