Back to interview questions

100+ Redux Interview Questions and Answers

100+ Redux Interview Questions and Answers

Explore 120 Redux interview questions and answers covering Redux Toolkit, selectors, async requests, RTK Query caching, testing and state architecture.

Explore 120 Redux interview questions and answers covering Redux Toolkit, selectors, async requests, RTK Query caching, testing and state architecture.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

Redux interviews should reveal whether a developer can explain how a user action becomes a predictable state transition and how that transition remains correct when requests race, components rerender or sessions change. Hiring teams need evidence of state modeling, async reasoning and practical debugging, alongside familiarity with Redux Toolkit, React-Redux and RTK Query.

These 100+ Redux Interview Questions and Answers cover 120 questions across beginner, intermediate and experienced levels. The bank moves from stores, actions and reducers to selectors, request lifecycles, caching, server rendering and production architecture. Choose questions that match the role’s responsibilities and the application’s actual rendering and data-fetching stack.

How can recruiters distinguish practical Redux expertise from memorized API definitions?

Give the candidate a concrete failure: an older search result replaces a newer one, a list stays stale after an update or one user’s cached data survives a session change. Ask them to trace ownership, actions, subscriptions and request identity, then explain a test that would expose the bug. Strong answers connect a specific mechanism to a user-visible outcome and acknowledge what the client cannot guarantee about the server.

Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation and unauthorized assistance during remote interviews. Pair those signals with a short state-modeling exercise, code discussion and follow-up questions about the candidate’s decisions. Review the evidence in context rather than treating one signal as conclusive proof of misconduct.

Redux Interview Questions

Use this complete question bank to select a balanced interview. The numbered answers that follow match the questions exactly, so interviewers can move from a foundational definition to a concrete debugging or design discussion.

Redux Interview Questions for Beginners

Assess core state ownership, action and reducer semantics, store behavior and the purpose of the modern Redux tools.

  1. What problem does Redux solve?

  2. How does unidirectional data flow work in Redux?

  3. What is Redux state?

  4. What is a Redux action?

  5. What is the difference between an action and an action creator?

  6. What does a reducer do?

  7. What is the Redux store responsible for?

  8. What happens when you dispatch an action?

  9. When would you use getState?

  10. What does store.subscribe provide?

  11. Why is Redux Toolkit recommended for modern Redux development?

  12. What does configureStore do?

  13. What does createSlice generate?

  14. How is a slice's location in the root state determined?

  15. How should reducer initial state be defined?

  16. How should a reducer handle an action it does not recognize?

  17. Why must reducers avoid side effects?

  18. Why does Redux rely on immutable updates?

  19. Why can createSlice reducers appear to mutate state?

  20. When should a Toolkit case reducer return a new value?

  21. What should an action payload contain?

  22. What is a prepare callback in createSlice useful for?

  23. How do reducers and extraReducers differ in createSlice?

  24. Why normalize relational application state?

  25. Why are serializable values recommended in Redux state and actions?

  26. What state should remain local to a React component?

  27. Why should derived data usually be calculated instead of stored twice?

  28. What is a selector?

  29. What does the React Redux Provider do?

  30. How does useSelector work?

  31. What does useDispatch return?

  32. Why does reference equality matter for React Redux performance?

  33. What is a thunk in Redux?

  34. What does createAsyncThunk provide?

  35. How should loading state be modeled?

  36. How should errors be represented in Redux?

  37. What is Redux middleware?

  38. How do Redux DevTools help with debugging?

  39. What is RTK Query designed to handle?

  40. How should a Redux feature be tested?

Redux Interview Questions for Intermediate

Explore immutable updates, typed integration, selectors, asynchronous requests and practical RTK Query behavior.

  1. How do you update a deeply nested object without losing unrelated state?

  2. How should a reducer add, remove or reorder array items?

  3. What changes when a slice's state is a primitive value?

  4. How do you reset a slice to its initial state?

  5. How can one event update several slices without dispatching many setter actions?

  6. Why can a selector that returns a new object cause unnecessary rendering?

  7. How does a memoized selector differ from an ordinary selector?

  8. How do you design a selector that accepts an item ID or other parameter?

  9. What does createEntityAdapter provide?

  10. Are entity-adapter updates deep merges?

  11. How should sorted entity collections be maintained?

  12. Why use unwrap when dispatching createAsyncThunk?

  13. When should createAsyncThunk use rejectWithValue?

  14. How can you prevent an older request from overwriting a newer result?

  15. How does cancellation work with createAsyncThunk?

  16. What is the purpose of a thunk's condition option?

  17. Why does middleware order matter?

  18. When is listener middleware useful?

  19. How should serializability warnings be handled?

  20. How do you type Redux hooks in a TypeScript application?

  21. What wiring does an RTK Query API need in a store?

  22. How do RTK Query queries and mutations differ?

  23. What determines whether two RTK Query consumers share cached data?

  24. What happens when the last subscriber leaves a query?

  25. How do tags support automated refetching?

  26. Why use an abstract LIST tag in addition to entity IDs?

  27. Does invalidating a tag always start a network request immediately?

  28. How do you implement an optimistic update safely?

  29. When is a pessimistic cache update preferable?

  30. What does selectFromResult accomplish?

  31. How do skip and skipToken prevent an unwanted query?

  32. How do data and currentData differ in a query hook?

  33. How should polling be configured and evaluated?

  34. What is needed for refetching on focus or reconnect?

  35. When should transformResponse be used?

  36. What cache decisions matter for paginated data?

  37. Does RTK Query create a single normalized cache for every entity?

  38. How should query caches be handled when a user logs out?

  39. How do you prevent RTK Query state and subscriptions from leaking between tests?

  40. How would you migrate a legacy Redux application incrementally?

Redux Interview Questions for Experienced

Assess architecture, concurrency, server rendering, lifecycle management, security boundaries and production diagnosis.

  1. How would you choose slice boundaries in a large application?

  2. How can state-machine thinking improve Redux state design?

  3. When should actions describe events rather than setters?

  4. How would you implement undo and redo?

  5. What risks arise when persisting Redux state across application versions?

  6. How would you synchronize state across browser tabs?

  7. Why should server-rendered requests avoid sharing one global store?

  8. How do you avoid hydration mismatches with Redux state?

  9. How should Redux be used with React Server Components?

  10. What should be considered when injecting reducers dynamically?

  11. How does endpoint injection help code splitting with RTK Query?

  12. When are multiple RTK Query API slices justified?

  13. How can streaming updates be integrated into an RTK Query cache entry?

  14. Why can overlapping optimistic updates make rollback unsafe?

  15. How should a client handle a timed-out write that may have succeeded?

  16. How do you reconcile temporary IDs after an optimistic creation?

  17. How would you prevent several expired requests from all refreshing a token?

  18. What contract must a custom RTK Query baseQuery follow?

  19. How do selector cache lifetime and memory use affect architecture?

  20. Why might a selector need to be draft-safe inside an Immer reducer?

  21. Does batching make several dispatched actions one atomic transaction?

  22. How do listener cancellation and task coordination work in practice?

  23. What limitation applies to getOriginalState in listener middleware?

  24. How can custom asynchronous middleware break dispatch callers?

  25. How should Redux DevTools and action logging handle sensitive data?

  26. How would you design an offline mutation queue?

  27. Where should sockets, timers and other resource handles live?

  28. How would you implement a global reset without erasing everything indiscriminately?

  29. How do you test debounced or delayed Redux workflows reliably?

  30. What makes a reducer deterministic, and how would you test it?

  31. How would you investigate slow updates in a very large collection?

  32. Where should search debouncing and request freshness rules live?

  33. How should a Redux-backed UI handle out-of-order stream events?

  34. How would you investigate excessive RTK Query cache memory?

  35. How would you approach a Redux ecosystem upgrade?

  36. Why can React Strict Mode expose duplicate-request or cleanup bugs?

  37. Why should components avoid dispatching during render?

  38. Can Redux action history serve as a reliable business audit log?

  39. When might multiple Redux stores be appropriate?

  40. How would you design Redux state for a collaborative task editor?

Redux Interview Questions and Answers

The answers describe recommended reasoning and illustrative designs, not a requirement to use Redux for every application. Examples distinguish plain reducers from Immer-powered case reducers and client state from authoritative server behavior. Adapt integration details to the installed library versions and framework lifecycle.

Redux Interview Questions and Answers for Beginners

These answers establish the contracts that make later async, cache and performance decisions understandable.

1. What problem does Redux solve?

Redux provides a predictable way to manage shared application state through explicit actions and reducer updates. It makes the path from an event to a state change inspectable and testable. Redux is not a user-interface framework, database or automatic solution for every asynchronous problem.

I would consider it when several features need coordinated client state or when complex updates benefit from a consistent model. A small component's open-menu flag may be simpler as local state. The useful question is whether a shared state architecture reduces complexity in this application, not whether every React project should install Redux.

2. How does unidirectional data flow work in Redux?

A user interaction or another event causes an action to be dispatched. Middleware can handle relevant effects, reducers calculate the next state, and subscribed UI consumers read that state to render the next view. The direction is explicit: the view does not directly mutate the store data that it displays.

For a quantity control, the click handler dispatches an increment event, the reducer applies the quantity rule and the component selects the resulting quantity. If the displayed value is wrong, I can trace that chain instead of guessing which component changed a shared object. An asynchronous operation introduces later lifecycle actions into the same flow; it does not make a reducer wait for a network response.

3. What is Redux state?

State is the application's current data snapshot managed by the store. It should represent the information needed for the intended behavior, with a structure that supports understandable updates and selection. It is not a place to put every object the application creates.

A task application might store task entities, the selected task ID and a filter. It can derive the filtered list rather than maintain another copy. I would keep transient resources such as socket connections outside ordinary state and store meaningful serializable status instead. Clear ownership prevents the same fact from drifting across several competing representations.

4. What is a Redux action?

An action is a plain object describing something that happened or an intended state transition, with a string type and optional additional data. Reducers interpret actions to calculate the next state. An action's descriptive name helps developers understand the event without inspecting every consumer.

A taskAdded action might carry the new task's ID and title. Dispatching it does not itself specify which component must rerender; state updates and subscriptions determine that. I would avoid treating action names as arbitrary labels because they form an important part of debugging and the communication contract between features.

5. What is the difference between an action and an action creator?

An action is the object dispatched to the store; an action creator is a function that produces that object. Redux Toolkit generates action creators for createSlice reducers, reducing repetitive type and payload construction. Calling a normal action creator alone does not update the store.

If taskAdded returns an action, dispatch(taskAdded(task)) sends it through the store pipeline. Forgetting dispatch leaves the state unchanged even though the returned object looks correct. A thunk action creator differs because it returns a function for middleware to execute, so I would explain the kind of value produced rather than assume every action creator has identical behavior.

6. What does a reducer do?

A reducer calculates the next state from the previous state and an action. It should be synchronous and free of side effects, returning the existing state when the action does not require a change. This contract makes updates predictable and permits focused tests of domain rules.

For a quantity increment, the reducer can compute the new value from the current quantity and payload. It should not send an HTTP request or generate a random ID during that calculation. Those values can be obtained before dispatch and included in the action, allowing the same inputs to reproduce the same transition.

// Plain reducer: deterministic and independently executable.
function counter(state = 0, action) {
  return action.type === 'counter/increment' ? state + 1 : state;
}
console.assert(counter(2, { type: 'counter/increment' }) === 3);
console.assert(counter(2, { type: 'unrelated/event' }) === 2);
// Plain reducer: deterministic and independently executable.
function counter(state = 0, action) {
  return action.type === 'counter/increment' ? state + 1 : state;
}
console.assert(counter(2, { type: 'counter/increment' }) === 3);
console.assert(counter(2, { type: 'unrelated/event' }) === 2);
// Plain reducer: deterministic and independently executable.
function counter(state = 0, action) {
  return action.type === 'counter/increment' ? state + 1 : state;
}
console.assert(counter(2, { type: 'counter/increment' }) === 3);
console.assert(counter(2, { type: 'unrelated/event' }) === 2);

7. What is the Redux store responsible for?

The store holds the current state, accepts dispatched actions and lets subscribers observe updates. It connects the reducer to middleware and other store behavior. Components should use the supported integration rather than modify the store's state object directly.

A typical application creates one store for its client-side application scope. Server rendering requires careful per-request ownership instead of sharing customer data through a process-wide singleton. The store is an in-memory runtime object; using Redux does not automatically persist state across reloads or synchronize it with another browser tab.

8. What happens when you dispatch an action?

Dispatch sends a value through the configured middleware pipeline. A normal action that reaches the base store is processed synchronously by the root reducer, and subscribers are notified after the state is updated. Middleware can add behavior or handle other values such as thunk functions.

After a plain synchronous action completes, getState reflects its reducer result. That does not mean a network request initiated by middleware has completed or React has already committed a render. I would distinguish dispatch processing, asynchronous work and UI rendering instead of describing them as one indivisible operation.

9. When would you use getState?

getState reads the current store state at the moment it is called. It is useful inside thunks, middleware or other integration code that needs a snapshot for a decision. Calling it does not subscribe the caller to future changes.

A thunk can inspect whether a request is already active before starting another operation. However, a value read before an await may no longer represent the current state afterward. I would reread when the later decision requires fresh information, while recognizing that a local state check cannot enforce a server-side concurrency or authorization guarantee.

10. What does store.subscribe provide?

subscribe registers a callback that runs after dispatch updates have been processed, allowing the subscriber to read the current state. It returns an unsubscribe function for cleanup. The callback is not automatically given the action or a state diff.

React applications normally rely on React Redux rather than manually wiring each component to subscribe. For a separate integration, I would track the value of interest and unsubscribe when its owner is disposed. Dispatching from a subscription requires a careful condition; an unconditional dispatch can create a loop even when the reducer itself is correct.

11. Why is Redux Toolkit recommended for modern Redux development?

Redux Toolkit supplies the standard tools for store setup, slice reducers, immutable updates and common async patterns. It reduces boilerplate while preserving Redux's core model of actions and state transitions. It also includes RTK Query for server-data fetching and caching.

I would start a new Redux feature with configureStore and createSlice rather than handwritten action-type constants and store setup unless a specific constraint requires otherwise. Toolkit is not a separate state system that replaces Redux concepts. Understanding reducer purity, references and middleware still matters when diagnosing behavior that helper functions make easier to express.

12. What does configureStore do?

configureStore creates a Redux store with useful defaults, including reducer combination for an object of slice reducers, thunk middleware and development checks. It also configures Redux DevTools support. Custom middleware or enhancer configuration should preserve intended defaults unless there is a reason to change them.

If I pass a reducer object with a cart key, that key determines the corresponding root-state field. I would inspect the configured middleware when an async dispatch or warning behaves unexpectedly. Replacing the middleware list with a custom array can remove default behavior, so the callback using getDefaultMiddleware is often the clearer extension point.

import { configureStore, createSlice } from '@reduxjs/toolkit';
const counter = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: { increment(state) { state.value += 1; } }
});
const store = configureStore({ reducer: { counter: counter.reducer } });
store.dispatch(counter.actions.increment());
console.assert(store.getState().counter.value === 1);
import { configureStore, createSlice } from '@reduxjs/toolkit';
const counter = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: { increment(state) { state.value += 1; } }
});
const store = configureStore({ reducer: { counter: counter.reducer } });
store.dispatch(counter.actions.increment());
console.assert(store.getState().counter.value === 1);
import { configureStore, createSlice } from '@reduxjs/toolkit';
const counter = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: { increment(state) { state.value += 1; } }
});
const store = configureStore({ reducer: { counter: counter.reducer } });
store.dispatch(counter.actions.increment());
console.assert(store.getState().counter.value === 1);

13. What does createSlice generate?

createSlice defines a slice name, initial state and case reducers, then generates the reducer and action creators associated with those named cases. Its reducers use Immer to support immutable updates through draft syntax. It groups related state behavior without requiring separate files for each action constant.

For a cart slice, addItem and removeItem cases can express the supported transitions. I would export the actions and reducer deliberately and keep external effects elsewhere. The slice name contributes to generated action types; it does not by itself determine where a manually registered reducer is mounted in the root store.

14. How is a slice's location in the root state determined?

For a reducer object passed to configureStore, the object's key determines the root-state location. That location can differ from the slice name used in generated action types. Newer slice injection and selector helpers also have reducerPath behavior that should be understood in the setup actually used.

If a slice named basket is registered under cart, manually written selectors read state.cart, not state.basket. Confusing the action prefix with the state path often produces undefined values. I would verify the store configuration and any injection helpers before changing a selector or renaming state to match an assumption.

15. How should reducer initial state be defined?

Define a valid state shape that handles the application before data arrives and supports the expected transitions. A reducer uses its initial value when called with undefined state. Meaningful initial state avoids forcing components to guess whether a field is absent accidentally or intentionally unavailable.

A request state might begin with status idle, data null and error null rather than several unrelated booleans. I would distinguish not-yet-loaded data from a valid empty result. If initialization reads persisted data, it should use a deliberate setup or supported lazy initialization path, with validation rather than assuming old stored values still fit the current schema.

16. How should a reducer handle an action it does not recognize?

It should return the current state unchanged. Redux sends actions through the root reducer, so many slice reducers will see events they do not handle. An unknown action is not a reason to reset state or throw merely because another feature dispatched it.

A reducer test should verify that an unrelated action preserves the relevant state reference when no change is needed. If the reducer returns undefined for an unknown action, it violates the expected contract and can break store initialization or combination. Returning the existing value also helps reference-based selection avoid unnecessary work.

17. Why must reducers avoid side effects?

Reducers need to calculate state deterministically from their inputs. Network calls, timers, random generation and external mutations make the transition depend on conditions outside those inputs. That undermines replay, debugging and reliable tests.

If a new record needs an ID and timestamp, generate them in an action preparation step or another appropriate boundary and carry them in the action. The reducer can then store those explicit values. A pure reducer does not imply the application has no side effects; it means effects have a separate, deliberate home such as a thunk or listener.

18. Why does Redux rely on immutable updates?

Immutable updates preserve the previous state and create new references for changed parts. This allows consumers to detect changes through reference comparisons and makes historical snapshots meaningful. Mutating a shared object can make old and new state appear identical while their contents have silently changed.

For a nested update written without Immer, every changed ancestor must be copied, while untouched branches can retain references. Deep-cloning the entire state is usually unnecessary and can cause avoidable rerenders. The goal is accurate structural sharing: new references where meaning changed and stable references where it did not.

19. Why can createSlice reducers appear to mutate state?

createSlice uses Immer, which supplies a draft for draftable state and records the changes to produce an immutable result. Assigning to a draft field is therefore different from mutating the original Redux state outside that controlled reducer context. The syntax is convenient, but the underlying state contract remains immutable.

I would explain that state.items.push(item) is supported inside an appropriate Toolkit case reducer, while pushing into an array returned by getState is not. The protection is scoped to Immer's draft processing; it does not make arbitrary objects elsewhere safe to mutate or permit effects inside the reducer.

20. When should a Toolkit case reducer return a new value?

Return a replacement when the whole slice value should be replaced, especially for primitive state or a reset to a new structure. For draftable state, a case reducer can instead modify the draft. It should not both mutate the draft and return a conflicting replacement in the same execution.

Assigning state = newValue only changes the local variable and does not replace the slice unless the function returns that value. For an array case, an implicit return from push can accidentally return a number after mutating the draft. A block-bodied function that only performs the intended draft update avoids that mistake.

// Two valid alternatives inside createSlice reducers:
const incrementDraft = (state) => { state.value += 1; };
const replaceCounter = (state) => ({ value: state.value + 1 });
// Do not mutate the draft AND return a different state in one case reducer.
// Two valid alternatives inside createSlice reducers:
const incrementDraft = (state) => { state.value += 1; };
const replaceCounter = (state) => ({ value: state.value + 1 });
// Do not mutate the draft AND return a different state in one case reducer.
// Two valid alternatives inside createSlice reducers:
const incrementDraft = (state) => { state.value += 1; };
const replaceCounter = (state) => ({ value: state.value + 1 });
// Do not mutate the draft AND return a different state in one case reducer.

21. What should an action payload contain?

A payload should contain the information needed to describe the event or perform the state transition, using a clear and stable shape. Include relevant domain data rather than a UI component instance or an arbitrary collection of unrelated values. Serializable values support inspection and predictable handling.

For a quantity change, an item ID and the requested quantity may be sufficient. Passing the entire current state makes the action harder to reason about and may carry stale or unnecessary data. I would also distinguish an event's facts from derived values the reducer or selector can calculate consistently.

22. What is a prepare callback in createSlice useful for?

A prepare callback builds the action payload and optional metadata before the reducer receives it. It lets the public action creator accept convenient arguments while producing a consistent action object. Work such as generating an ID can occur here instead of inside the reducer.

For adding a note, prepare can accept text and create a payload containing an ID and the text. The case reducer then handles the explicit payload deterministically. I would keep preparation focused on action construction; a workflow involving network requests or waiting belongs in an appropriate async mechanism rather than being hidden in an ordinary action creator.

23. How do reducers and extraReducers differ in createSlice?

The reducers field defines cases that generate corresponding action creators for that slice. extraReducers lets the slice respond to actions defined elsewhere, such as async thunk lifecycle actions, without generating new action creators for them. Both participate in the slice's state transitions and use Immer behavior.

A session-cleared event can be handled by several slices through extraReducers so each resets its own relevant state. I would use the current builder callback form and explicit event semantics. Responding to a shared event does not mean one slice reducer should directly call another slice's action creator and expect dispatch to happen automatically.

24. Why normalize relational application state?

Normalization stores each entity in a keyed collection and represents relationships with IDs, reducing duplicated copies of the same record. It can make updates and lookups more predictable when many views use related data. It is a modeling choice, not a requirement to turn every small value into a database-like table.

If the same user appears in several posts, storing one user record can avoid updating many embedded copies when the display name changes. Selectors can assemble the view the UI needs. I would still define ownership and deletion behavior explicitly; normalization alone does not enforce referential integrity or synchronize remote data.

25. Why are serializable values recommended in Redux state and actions?

Serializable values support debugging, persistence, replay and predictable comparisons. Functions, promises, class instances and live resource handles often carry behavior or identity that cannot be represented faithfully as ordinary data. Toolkit's development middleware can warn about common violations.

Instead of storing a Date instance, an application can store an agreed timestamp representation and format it at the boundary. A socket connection can live in an effect-owning service while Redux stores connection status. Middleware may intentionally intercept nonserializable values before reducers, but that exception should be deliberate rather than a reason to disable all checks.

Value

Ordinary state representation

Reason

Date object

ISO timestamp string or epoch number

Portable representation with explicit conversion at boundaries

Socket connection

Connection status and safe identifier

Keep the live handle in its lifecycle owner

Error instance

Defined plain error fields

Preserve relevant information without depending on prototype properties

26. What state should remain local to a React component?

State that belongs only to one component or a small local subtree often fits React state better than the global store. Examples include an unshared input draft or a temporary disclosure state. Use the narrowest ownership that supports the actual sharing, lifetime and debugging needs.

A form's unsaved keystrokes may remain local until submission, while a committed entity belongs in shared state or a server cache. If navigation or another feature must preserve the draft, the ownership decision may change. I would avoid moving every value to Redux simply for consistency because global lifetime and updates can create unnecessary coupling.

27. Why should derived data usually be calculated instead of stored twice?

A value that can be calculated from existing state can often be derived through a selector, avoiding synchronization rules for duplicate representations. Storing both a list and its filtered version creates opportunities for one to change without the other. The calculation's cost and ownership should still be considered.

For a cart, the item count can be derived from quantities rather than maintained by every add, remove and reset action. If the calculation is expensive, memoization may help. I would not confuse a derived display total with an authoritative server-calculated amount that includes rules the client cannot reproduce; those are different facts with different owners.

28. What is a selector?

A selector is a function that reads state and returns a value needed by a consumer. It can encapsulate the state shape and derive useful data. A selector does not need to be memoized merely because it is called a selector.

A selectSelectedTask function can read the selected ID and return the corresponding entity, keeping components independent of the storage layout. It should be pure and safe to call repeatedly. If a selector creates a new object on every call, consumers using reference equality may see a change even when the underlying data is unchanged.

29. What does the React Redux Provider do?

Provider makes a particular Redux store available to React Redux consumers in its subtree through context. Hooks such as useSelector and useDispatch access that configured store. Provider does not automatically put every component value into Redux or replace the need to define reducers.

I would ensure the intended store instance has a stable lifetime for the application scope. Creating a new store on every ordinary render can reset state and subscriptions. In server-rendered environments, that lifetime must also avoid sharing mutable request-specific state across users; a global singleton is not automatically the right setup.

30. How does useSelector work?

useSelector runs a selector against the store state and subscribes the component to relevant updates. By default, it compares the selected result using strict reference equality to decide whether the store update requires a rerender. The selector should be pure because it may run multiple times.

Selecting a primitive or stable entity reference usually gives a clear change boundary. Returning a freshly created object every time can cause rerenders even when its fields have not changed. I would use separate selections, an appropriate equality function or a memoized selector depending on the result, rather than assume useSelector shallow-compares every object automatically.

31. What does useDispatch return?

useDispatch returns the dispatch function from the store supplied by Provider. Components use it to send actions or supported middleware-handled values. It does not bind every action creator automatically or decide which state a component reads.

In a TypeScript application, a typed dispatch hook can expose the store's actual dispatch capabilities, including thunks. I would keep event handling separate from rendering and dispatch when the user interaction or intended lifecycle requires it. Calling an action creator without dispatch, or dispatching continuously during render, produces very different behavior from a normal event handler.

32. Why does reference equality matter for React Redux performance?

Reference equality provides a cheap signal of whether selected data changed, but it relies on correct immutable updates and stable derived results. Mutating an existing object can hide a real change, while allocating equivalent new objects can signal a change that is not meaningful. Both problems can appear as UI behavior issues.

I would inspect the reducer's structural sharing and the selector's output before adding memoization everywhere. A component selecting one entity should not need to rerender because an unrelated entity changed if the references are preserved appropriately. Parent renders and local state can still cause renders, so store selection is only one part of the performance picture.

33. What is a thunk in Redux?

A thunk is a function handled by thunk middleware that can use dispatch and getState to perform logic, including asynchronous work. It provides a place for effects outside reducers. Dispatching a thunk returns the value the thunk returns, which may be a promise if the thunk is async.

A thunk can load data, inspect current state and dispatch result actions. It does not automatically provide caching, cancellation or duplicate-request prevention; those behaviors need implementation or a higher-level tool. For routine server-data fetching, RTK Query may remove work that would otherwise be repeated across many thunks.

34. What does createAsyncThunk provide?

createAsyncThunk creates an async action workflow that dispatches pending, fulfilled and rejected lifecycle actions around a payload creator. It supplies useful metadata such as a request ID and supports cancellation-related APIs. It does not generate the reducer state that tracks loading or automatically cache requests by argument.

I would handle the lifecycle in extraReducers and define how this feature represents idle, loading, success and failure. If several requests can overlap, the reducer needs an explicit acceptance policy for results. The helper makes the lifecycle consistent, but it cannot decide which response should win for the application's domain.

35. How should loading state be modeled?

Model loading with a state shape that distinguishes meaningful phases and avoids contradictory combinations. A status field is often clearer than several booleans that can all become true. Keep existing data and refresh state separate when the UI should display stale data during a new request.

For a first load, the interface may show an initial placeholder; for a refresh, it may retain the current list with an updating indicator. I would also define what happens after rejection and on retry. A single global isLoading flag is often insufficient when unrelated requests or several entity-specific operations can run at once.

36. How should errors be represented in Redux?

Store the serializable error information the UI or workflow needs, with a clear distinction between expected domain failures and unexpected technical failures. Avoid placing raw Error objects or sensitive server details into state by default. Error handling should support a meaningful next action rather than only displaying an arbitrary message.

A validation failure might carry field-level information, while a network failure may support retry. I would clear or retain the error deliberately when another request begins, and avoid showing an earlier request's error after a later request succeeded. The error contract should be consistent across the API boundary and the reducer.

37. What is Redux middleware?

Middleware wraps dispatch to observe, transform or handle dispatched values and coordinate effects before they reach the base store. Each middleware receives store access and the next function in the chain. The composition order matters, and calling next is different from starting again through dispatch.

A logging middleware can inspect an action before and after next(action) to compare state. I would avoid logging secrets and preserve the return value when the middleware is only observing. If it swallows an action intentionally, that behavior needs a clear contract; otherwise downstream middleware and reducers may never see the event.

38. How do Redux DevTools help with debugging?

DevTools let developers inspect dispatched actions and state changes, making it easier to trace how the application reached a particular state. They are especially useful when event names and payloads reflect the domain. They do not automatically explain external effects or guarantee that replaying state recreates network behavior.

I would use the action sequence to locate the first unexpected transition, then inspect the reducer and async workflow involved. Time travel can reveal state differences but cannot undo a payment or another remote side effect. Sensitive data should not be placed casually into actions or logs simply because the tooling makes inspection convenient.

39. What is RTK Query designed to handle?

RTK Query manages server-data fetching and caching, including request status, subscriptions and refetching behavior. It is part of Redux Toolkit and can generate React hooks when using the React-specific entry point. It reduces the need to write repeated request lifecycle reducers manually.

I would use it for data whose source of truth is an API, while keeping unrelated client workflow state in suitable local state or slices. Its cache is not a universal normalized database that automatically merges every entity across every endpoint. Understanding cache keys and invalidation remains necessary for reliable behavior.

40. How should a Redux feature be tested?

Test the observable behavior with a real configured store where practical, and use focused unit tests for reducers or selectors whose rules benefit from isolation. Integration tests should exercise the component and state interaction rather than mock away every Redux hook. Network behavior can be controlled at an appropriate boundary.

For a save form, a useful test checks the pending state, successful result and error path under representative responses. Each test should get a fresh store to avoid leaked state. A passing reducer test establishes that transition for the supplied inputs; it does not prove the rendered workflow, API contract or browser behavior works end to end.

Redux Interview Questions and Answers for Intermediate

These answers connect individual APIs to realistic application bugs, including stale results, unstable references and incomplete cache invalidation.

41. How do you update a deeply nested object without losing unrelated state?

Outside an Immer-powered reducer, copy every ancestor along the changed path and preserve untouched branches. A shallow copy of only the root still shares nested objects, so changing a nested property can mutate the previous state. In a createSlice reducer, an equivalent assignment to the draft is supported, but the domain structure still needs to make sense.

For a shipping address, I would update the city while preserving the customer's other details and other customers' references. A test should check the changed value, the unchanged old snapshot and the identity of an unaffected branch. If updates routinely require navigating many levels, normalization may improve the model instead of merely shortening the update syntax.

const before = {
  customer: { address: { city: 'Pune', postalCode: '411001' } },
  preferences: { theme: 'dark' }
};
const after = {
  ...before,
  customer: {
    ...before.customer,
    address: { ...before.customer.address, city: 'Mumbai' }
  }
};
console.assert(before.customer.address.city === 'Pune');
console.assert(after.customer.address.postalCode === '411001');
console.assert(after.preferences === before.preferences);
const before = {
  customer: { address: { city: 'Pune', postalCode: '411001' } },
  preferences: { theme: 'dark' }
};
const after = {
  ...before,
  customer: {
    ...before.customer,
    address: { ...before.customer.address, city: 'Mumbai' }
  }
};
console.assert(before.customer.address.city === 'Pune');
console.assert(after.customer.address.postalCode === '411001');
console.assert(after.preferences === before.preferences);
const before = {
  customer: { address: { city: 'Pune', postalCode: '411001' } },
  preferences: { theme: 'dark' }
};
const after = {
  ...before,
  customer: {
    ...before.customer,
    address: { ...before.customer.address, city: 'Mumbai' }
  }
};
console.assert(before.customer.address.city === 'Pune');
console.assert(after.customer.address.postalCode === '411001');
console.assert(after.preferences === before.preferences);

42. How should a reducer add, remove or reorder array items?

Use immutable array operations in an ordinary reducer, or draft operations inside an Immer-powered case reducer. Adding with spread, removing with filter and creating a copied array before sorting preserve the original array. Inside createSlice, push, splice and sort can operate on the draft safely.

For a reorder action, I would carry stable item IDs or an explicit final order and validate missing or duplicate IDs according to the domain. Array indexes are fragile identifiers when another update inserts an item. Tests should include no-op removals, boundary positions and preservation of unrelated item objects, rather than checking only the final array length.

43. What changes when a slice's state is a primitive value?

A primitive value cannot be mutated through an Immer draft. A case reducer whose state is a number, string or boolean must return the next value. Writing state += 1 without returning the result only changes the local parameter; it does not communicate replacement state to Redux Toolkit.

For a numeric counter, return state + 1 is clear. For an object-shaped counter, state.value += 1 changes a draft property instead. I would choose the state shape based on the information the feature needs, not solely to obtain preferred syntax, and test both increment and reset behavior to catch an accidentally missing return.

import { createSlice } from '@reduxjs/toolkit';
const counter = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
    reset: () => 0
  }
});
console.assert(counter.reducer(4, counter.actions.increment()) === 5);
import { createSlice } from '@reduxjs/toolkit';
const counter = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
    reset: () => 0
  }
});
console.assert(counter.reducer(4, counter.actions.increment()) === 5);
import { createSlice } from '@reduxjs/toolkit';
const counter = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
    reset: () => 0
  }
});
console.assert(counter.reducer(4, counter.actions.increment()) === 5);

44. How do you reset a slice to its initial state?

Return an appropriate initial value from the case reducer. Assigning a new object to the local state variable is not a replacement return. For an initial state that depends on runtime inputs, use a deliberate factory or explicit reset payload rather than assuming that a module-level object will refresh itself.

An editor reset might restore empty fields while preserving a separately owned account preference. I would define that boundary before implementing reset, then test that stale selection and validation state disappear together. Do not generate timestamps or read storage unpredictably inside the reducer to achieve a reset; obtain external information before the transition and make the intended state explicit.

45. How can one event update several slices without dispatching many setter actions?

Several reducers can respond to the same domain action, commonly through extraReducers. The root reducer passes an action to each slice reducer, so one orderCompleted event can update an order record and clear a checkout selection in a single store transition. Slices do not need to import or call one another's reducers.

I would define a shared event contract containing the information each consumer actually needs. This avoids sequences of loosely coordinated setters that expose intermediate states. However, unrelated consequences such as sending analytics or navigating belong in side-effect handling, and a domain event should not become an enormous payload that couples every feature to internal details of all the others.

46. Why can a selector that returns a new object cause unnecessary rendering?

useSelector compares its selected result with the previous result using strict reference equality by default. Returning a fresh object or filtered array for an otherwise unchanged input produces a different reference. The component can therefore rerender after store updates even when the values it cares about have not changed.

I would first select stable fields separately, use an appropriate equality function, or memoize a genuine derived result. Merely wrapping the selector function in useCallback does not make its returned object stable. The fix should follow the actual computation and component boundary, and development selector checks can expose unstable output before a large screen makes the cost obvious.

47. How does a memoized selector differ from an ordinary selector?

A memoized selector can reuse a previously computed result when its relevant inputs have not changed. With createSelector, input selectors extract dependencies and the result function performs the derivation. This can avoid expensive repeated work and preserve the result reference for consumers that use reference equality.

For a visible task list, input selectors can return the task array and selected filter, while the result function applies the filter. Putting filter inside an input selector creates a new array and undermines the intended dependency stability. I would not memoize every property lookup: a direct lookup is already cheap, and unnecessary caching makes ownership and parameter behavior harder to understand.

import { createSelector } from '@reduxjs/toolkit';
const selectVisibleTasks = createSelector(
  [(state) => state.tasks, (state) => state.filter],
  (tasks, filter) => tasks.filter((task) =>
    filter === 'all' || task.status === filter
  )
);
const state = { tasks: [{ id: 1, status: 'open' }], filter: 'open' };
console.assert(selectVisibleTasks(state) === selectVisibleTasks(state));
import { createSelector } from '@reduxjs/toolkit';
const selectVisibleTasks = createSelector(
  [(state) => state.tasks, (state) => state.filter],
  (tasks, filter) => tasks.filter((task) =>
    filter === 'all' || task.status === filter
  )
);
const state = { tasks: [{ id: 1, status: 'open' }], filter: 'open' };
console.assert(selectVisibleTasks(state) === selectVisibleTasks(state));
import { createSelector } from '@reduxjs/toolkit';
const selectVisibleTasks = createSelector(
  [(state) => state.tasks, (state) => state.filter],
  (tasks, filter) => tasks.filter((task) =>
    filter === 'all' || task.status === filter
  )
);
const state = { tasks: [{ id: 1, status: 'open' }], filter: 'open' };
console.assert(selectVisibleTasks(state) === selectVisibleTasks(state));

48. How do you design a selector that accepts an item ID or other parameter?

Pass the parameter consistently through the selector's inputs and choose a cache lifetime that matches its callers. A simple entity lookup may need no memoization. A costly per-item derivation may benefit from a shared selector or a selector factory, depending on argument patterns and the configured memoizer.

For a row, useSelector can call selectTaskById(state, taskId). If a selector factory is used, create a stable instance for the component rather than recreating it on every render. I would avoid universal claims that all selectors cache only one result: Reselect behavior depends on the version and memoization options. Measure recomputation and retained memory for the actual workload.

49. What does createEntityAdapter provide?

createEntityAdapter provides a standard normalized collection shape, CRUD-style update helpers and selectors. The typical state contains ids and entities, with configurable ID selection and optional sorting. It reduces repeated collection bookkeeping but does not decide the application's business rules or fetch data automatically.

For tasks keyed by taskId, I would configure selectId and use upsertMany when a response should merge records. The adapter can coexist with fields such as loading status in the same slice. Before selecting an operation, clarify whether incoming data is a complete replacement, a partial update or a subset; choosing setAll for a partial page can unintentionally discard records the application still needs.

import { createEntityAdapter, createSlice } from '@reduxjs/toolkit';
const adapter = createEntityAdapter({ selectId: (task) => task.taskId });
const tasks = createSlice({
  name: 'tasks',
  initialState: adapter.getInitialState({ status: 'idle' }),
  reducers: { tasksReceived: adapter.upsertMany }
});
const next = tasks.reducer(undefined, tasks.actions.tasksReceived([
  { taskId: 't1', title: 'Review' }
]));
console.assert(next.entities.t1.title === 'Review');
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit';
const adapter = createEntityAdapter({ selectId: (task) => task.taskId });
const tasks = createSlice({
  name: 'tasks',
  initialState: adapter.getInitialState({ status: 'idle' }),
  reducers: { tasksReceived: adapter.upsertMany }
});
const next = tasks.reducer(undefined, tasks.actions.tasksReceived([
  { taskId: 't1', title: 'Review' }
]));
console.assert(next.entities.t1.title === 'Review');
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit';
const adapter = createEntityAdapter({ selectId: (task) => task.taskId });
const tasks = createSlice({
  name: 'tasks',
  initialState: adapter.getInitialState({ status: 'idle' }),
  reducers: { tasksReceived: adapter.upsertMany }
});
const next = tasks.reducer(undefined, tasks.actions.tasksReceived([
  { taskId: 't1', title: 'Review' }
]));
console.assert(next.entities.t1.title === 'Review');

50. Are entity-adapter updates deep merges?

No. Update and upsert helpers perform shallow changes to entity fields, so supplying a nested object can replace that nested field rather than merge every property within it. Assuming a deep merge can silently remove data such as an address's unchanged postal code.

I would normalize nested relationships where appropriate or explicitly construct the intended nested replacement before updating. If the server sends a patch format, translate that format into a well-defined reducer operation instead of assuming adapter semantics match it. Tests should use nested records with multiple properties so accidental field loss is visible, and distinguish absent fields from explicit null values when the API gives them different meanings.

51. How should sorted entity collections be maintained?

An entity adapter can maintain its IDs in an order determined by sortComparer when its helpers make relevant changes. The comparator should implement the desired stable domain ordering, including a deterministic tie-breaker where necessary. Consumers can then obtain ordered entities through the generated selectors.

For tasks ordered by due date, I would define how missing dates and equal dates behave and ensure the values are comparable. A display-specific sort chosen independently by each user may be better derived in a selector than imposed as the collection's canonical order. Sorting a selector's original state array in place is unsafe; preserve immutable inputs even when the visible output seems correct.

52. Why use unwrap when dispatching createAsyncThunk?

The promise returned by dispatching a createAsyncThunk resolves to the final fulfilled or rejected action. Calling unwrap extracts the fulfilled payload or throws the rejection payload or serialized error, allowing ordinary try/catch control flow in a caller that needs to react to success or failure.

For a save button, I would await dispatch(saveTask(input)).unwrap() before showing a success message or navigating away. Without unwrap or an explicit action-status check, awaiting dispatch alone can lead the caller to treat a rejected request as success. The component should still handle loading and cancellation deliberately; unwrap does not itself implement retries, deduplication or a server-side transaction.

import { configureStore, createAsyncThunk } from '@reduxjs/toolkit';
// Local asynchronous stand-in; no HTTP request is made.
const saveTask = createAsyncThunk('tasks/save', async (input) => ({
  ...input, saved: true
}));
const store = configureStore({ reducer: (state = {}) => state });
const saved = await store.dispatch(saveTask({ id: 't1' })).unwrap();
console.assert(saved.saved === true);
import { configureStore, createAsyncThunk } from '@reduxjs/toolkit';
// Local asynchronous stand-in; no HTTP request is made.
const saveTask = createAsyncThunk('tasks/save', async (input) => ({
  ...input, saved: true
}));
const store = configureStore({ reducer: (state = {}) => state });
const saved = await store.dispatch(saveTask({ id: 't1' })).unwrap();
console.assert(saved.saved === true);
import { configureStore, createAsyncThunk } from '@reduxjs/toolkit';
// Local asynchronous stand-in; no HTTP request is made.
const saveTask = createAsyncThunk('tasks/save', async (input) => ({
  ...input, saved: true
}));
const store = configureStore({ reducer: (state = {}) => state });
const saved = await store.dispatch(saveTask({ id: 't1' })).unwrap();
console.assert(saved.saved === true);

53. When should createAsyncThunk use rejectWithValue?

Use rejectWithValue when a request fails in an expected, structured way and the reducer or caller needs a defined error payload, such as field validation errors. Unhandled thrown errors are serialized into the rejected action's error field, which is useful but may not preserve application-specific details.

I would map an API validation response into a small serializable shape with field names and safe messages, then return rejectWithValue with that shape. Keep transport diagnostics and secrets out of user-facing payloads. Type the rejection contract where TypeScript is used, and distinguish validation, cancellation and unexpected failures so the interface does not display an alarming generic error for every unsuccessful outcome.

54. How can you prevent an older request from overwriting a newer result?

Track the relevant request ID or another explicit generation identifier and accept a completion only if it still belongs to the active request. createAsyncThunk supplies requestId metadata. The guard must match the scope of concurrency: a single global request ID may be wrong when several independent records load simultaneously.

For rapidly changing search text, the reducer can record the newest request and ignore older fulfilled or rejected actions. Cancellation can reduce wasted work, but a stale-result guard remains useful when cancellation is late or unsupported. I would test out-of-order completion deliberately, including an older failure arriving after a newer success, rather than relying on requests finishing in dispatch order.

// A plain reducer illustrating one active search request.
function search(state = { requestId: null, results: [] }, action) {
  if (action.type === 'search/pending') {
    return { ...state, requestId: action.meta.requestId };
  }
  if (action.type === 'search/fulfilled' &&
      action.meta.requestId === state.requestId) {
    return { ...state, results: action.payload };
  }
  return state;
}
const active = search(undefined, {
  type: 'search/pending', meta: { requestId: 'new' }
});
const ignored = search(active, {
  type: 'search/fulfilled', meta: { requestId: 'old' }, payload: ['stale']
});
console.assert(ignored === active);
// A plain reducer illustrating one active search request.
function search(state = { requestId: null, results: [] }, action) {
  if (action.type === 'search/pending') {
    return { ...state, requestId: action.meta.requestId };
  }
  if (action.type === 'search/fulfilled' &&
      action.meta.requestId === state.requestId) {
    return { ...state, results: action.payload };
  }
  return state;
}
const active = search(undefined, {
  type: 'search/pending', meta: { requestId: 'new' }
});
const ignored = search(active, {
  type: 'search/fulfilled', meta: { requestId: 'old' }, payload: ['stale']
});
console.assert(ignored === active);
// A plain reducer illustrating one active search request.
function search(state = { requestId: null, results: [] }, action) {
  if (action.type === 'search/pending') {
    return { ...state, requestId: action.meta.requestId };
  }
  if (action.type === 'search/fulfilled' &&
      action.meta.requestId === state.requestId) {
    return { ...state, results: action.payload };
  }
  return state;
}
const active = search(undefined, {
  type: 'search/pending', meta: { requestId: 'new' }
});
const ignored = search(active, {
  type: 'search/fulfilled', meta: { requestId: 'old' }, payload: ['stale']
});
console.assert(ignored === active);

55. How does cancellation work with createAsyncThunk?

The dispatched thunk promise exposes abort, and the payload creator receives an AbortSignal that can be passed to compatible work such as fetch. Aborting the thunk produces a rejected lifecycle result with cancellation metadata. Stopping the client request does not prove that a server-side operation was undone.

When a component no longer needs a read, its cleanup can abort the task and the reducer can avoid treating that cancellation as a user-visible failure. A write requires additional care: the server may already have committed it. I would reconcile uncertain write outcomes using the operation's identity or a fresh read rather than automatically retrying a potentially completed mutation.

56. What is the purpose of a thunk's condition option?

The condition option can decide whether a createAsyncThunk should begin, for example by checking whether matching work is already in progress or the data is sufficiently fresh. Returning false skips execution. Whether a condition rejection is dispatched is configurable through dispatchConditionRejection.

For a record fetch, I would inspect status keyed by that record ID instead of blocking all requests because some unrelated record is loading. A condition is a useful local gate, not a distributed lock or a guarantee that remote data is current. If caching and subscription behavior become elaborate, RTK Query may provide a clearer lifecycle than repeatedly rebuilding those rules in custom thunks.

57. Why does middleware order matter?

Middleware forms an ordered pipeline around dispatch. Each middleware can inspect an incoming value, pass it to next, dispatch additional actions, change the returned value or stop propagation. Its position determines which values and results it sees, including function values handled by thunk middleware.

I would preserve the defaults with getDefaultMiddleware when extending configureStore unless there is a clear reason to replace them. A logger before thunk may see a function while one after thunk sees the plain actions that the thunk dispatches. Custom middleware should normally return next(action)'s result; dropping that return can break callers that await a thunk promise or call its abort method.

// Middleware factory; report receives action types, not full payloads.
const makeTypeLogger = (report) => () => (next) => (action) => {
  if (typeof action === 'object' && action !== null) report(action.type);
  return next(action);
};
const token = { abort() {} };
const result = makeTypeLogger(() => {})({})(() => token)({ type: 'test' });
console.assert(result === token);
// Middleware factory; report receives action types, not full payloads.
const makeTypeLogger = (report) => () => (next) => (action) => {
  if (typeof action === 'object' && action !== null) report(action.type);
  return next(action);
};
const token = { abort() {} };
const result = makeTypeLogger(() => {})({})(() => token)({ type: 'test' });
console.assert(result === token);
// Middleware factory; report receives action types, not full payloads.
const makeTypeLogger = (report) => () => (next) => (action) => {
  if (typeof action === 'object' && action !== null) report(action.type);
  return next(action);
};
const token = { abort() {} };
const result = makeTypeLogger(() => {})({})(() => token)({ type: 'test' });
console.assert(result === token);

58. When is listener middleware useful?

Listener middleware is useful for reactive side effects triggered by actions or state changes. It can express workflows such as debounced saves, waiting for a related event or cancelling a previous task without putting effects in reducers. Its effect logic receives tools for coordinating asynchronous work.

For a preference change, a listener can wait briefly and persist the latest state, while reducers update the interface immediately. I would define whether newer changes cancel older persistence attempts and how errors are surfaced. A listener is not a substitute for a server-data cache: RTK Query is usually the more focused option for request caching, subscriptions and invalidation.

59. How should serializability warnings be handled?

Investigate what nonserializable value entered state or an action and whether it belongs there. Often the correct fix is to store an ID, timestamp string or plain data while keeping a resource handle outside the store. Disabling the check globally hides future mistakes and can make replay or persistence unreliable.

Some integrations intentionally place special values in narrowly defined action paths that middleware consumes. I would configure targeted exceptions only after understanding that contract, documenting why the value does not undermine the required tooling. An exception silences a diagnostic; it does not turn a Date, function or socket into portable JSON data or make arbitrary persistence safe.

60. How do you type Redux hooks in a TypeScript application?

Infer RootState and AppDispatch from the configured store and expose typed useSelector and useDispatch hooks for application components. Current React-Redux provides withTypes helpers for this purpose. Keeping those hook definitions in a separate module also helps avoid awkward runtime import cycles.

The dispatch type matters because the ordinary base dispatch type does not describe all thunk behavior. I would use type-only imports for the inferred types and let slice payload types describe domain inputs. Type safety does not validate a network response at runtime, so untrusted data still needs appropriate validation before the application relies on its shape.

61. What wiring does an RTK Query API need in a store?

Mount the API reducer at its reducerPath and add its middleware to the store's middleware chain. React applications using generated hooks should create the API through the React-specific entry point and provide the configured store through React-Redux. Each part serves a different purpose: cached state, lifecycle effects and UI subscriptions.

I would use computed property syntax for the reducerPath to avoid a spelling mismatch and preserve the default middleware when appending the API middleware. setupListeners enables the relevant focus and reconnect behavior when requested; it is not a replacement for the API middleware. A small integration test should confirm that a mounted consumer can request and display data, not merely that configuration code imports successfully.

import { configureStore } from '@reduxjs/toolkit';
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const api = createApi({
  reducerPath: 'productsApi',
  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
  endpoints: (build) => ({
    getProduct: build.query({
      query: (id) => `products/${encodeURIComponent(id)}`
    })
  })
});
const store = configureStore({
  reducer: { [api.reducerPath]: api.reducer },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(api.middleware)
});
export const { useGetProductQuery } = api;
export { store };
import { configureStore } from '@reduxjs/toolkit';
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const api = createApi({
  reducerPath: 'productsApi',
  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
  endpoints: (build) => ({
    getProduct: build.query({
      query: (id) => `products/${encodeURIComponent(id)}`
    })
  })
});
const store = configureStore({
  reducer: { [api.reducerPath]: api.reducer },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(api.middleware)
});
export const { useGetProductQuery } = api;
export { store };
import { configureStore } from '@reduxjs/toolkit';
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const api = createApi({
  reducerPath: 'productsApi',
  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
  endpoints: (build) => ({
    getProduct: build.query({
      query: (id) => `products/${encodeURIComponent(id)}`
    })
  })
});
const store = configureStore({
  reducer: { [api.reducerPath]: api.reducer },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(api.middleware)
});
export const { useGetProductQuery } = api;
export { store };

62. How do RTK Query queries and mutations differ?

Queries describe reading and subscribing to cached data, while mutations describe operations that change data and are explicitly triggered. Query subscriptions can share a cache entry based on the endpoint and serialized arguments. Mutation behavior does not automatically behave like a shared query subscription.

A product detail read belongs naturally in a query, while updating its price belongs in a mutation. After a successful update, invalidating relevant tags can refresh active queries. HTTP method alone is not the entire conceptual distinction: an API might use POST for a search, and the endpoint definition should reflect whether the operation is a cacheable read or a change with side effects.

Concern

Query

Mutation

Typical purpose

Read and subscribe to cached data

Trigger a change

Cache relationship

Endpoint plus serialized arguments

Separate mutation lifecycle; explicit sharing options exist

After a write

Affected subscribed entries can refetch

Invalidate tags or reconcile relevant cached results

63. What determines whether two RTK Query consumers share cached data?

The endpoint and serialized query arguments determine the query cache key. Consumers with the same key subscribe to the same cached entry rather than creating independent copies solely because they are different components. Custom serialization can change that behavior and therefore requires careful design.

For a product endpoint, IDs 10 and 11 should normally produce different entries, while two consumers of ID 10 can share one. Include every argument that changes the meaning of the response, such as tenant or locale when applicable. Excluding such a value from the key can display data from the wrong context even if the networking code itself sends the correct parameter.

64. What happens when the last subscriber leaves a query?

RTK Query normally retains unused cached data for the configured keepUnusedDataFor duration before removing it. A new subscriber during that window can reuse the entry, subject to refetch settings. The default retention is 60 seconds, but applications can configure it globally or per endpoint.

For a user moving between a list and a detail screen, retention can avoid unnecessary repeat requests. It is not the same as declaring the data fresh for that entire interval: retention and refetch policy answer different questions. I would tune them using navigation patterns, response size and freshness requirements rather than increasing retention indiscriminately for every endpoint.

65. How do tags support automated refetching?

Queries can provide tags that describe the data they contain, and mutations can invalidate relevant tags. RTK Query uses those relationships to identify affected cache entries; subscribed entries can refetch, while invalidated entries without active subscriptions can be removed. Tags are invalidation relationships, not database constraints.

For a product update, an entity-specific tag can refresh the detail and any list that provided that product's tag. The endpoint must actually provide the tag for the relationship to work. I would test both successful and failed mutations under the chosen invalidation policy and avoid invalidating every endpoint when a narrower relationship accurately describes the affected data.

66. Why use an abstract LIST tag in addition to entity IDs?

An abstract LIST tag represents a collection whose membership may change even when the affected entity was not previously present. Entity-specific tags help target existing records, while a collection tag can refresh a list after creation, deletion or a filter-relevant change that alters membership.

If a new task is created, the old list could not have provided that new task's ID. Invalidating its LIST tag gives the list a reason to refetch. I would choose an abstract identifier that cannot collide with real entity IDs and distinguish separate list scopes when required. Overly broad collection tags are simple but may create unnecessary traffic across unrelated views.

67. Does invalidating a tag always start a network request immediately?

No. The result depends on matching cache entries, active subscriptions and invalidation timing. Active affected queries can refetch, while unused affected entries can be removed instead. RTK Query also supports delayed invalidation behavior that can wait for pending requests to settle, so an immediate request is not guaranteed.

When debugging a stale screen, I would inspect whether the query provided the expected tag, the mutation invalidated it, a subscription remains active and ongoing requests affect timing. Repeatedly adding manual refetch calls can conceal a broken tag relationship. The desired outcome is correct data after the mutation, with a clear lifecycle, rather than simply observing any extra request in the network panel.

68. How do you implement an optimistic update safely?

Apply a predicted cache change in onQueryStarted using updateQueryData, retain the patch result and await queryFulfilled. If the operation fails, undo the patch when that rollback is safe or invalidate the relevant data so the server becomes the source of truth. Optimism should be an explicit user-experience decision.

For a simple isolated toggle, immediate feedback with rollback can work well. With overlapping updates, undoing one failed patch can interfere with a later successful edit, so refetching or a more deliberate reconciliation model may be safer. I would also display pending or failed state where it matters; an optimistic interface must not imply that an unconfirmed server operation has definitely completed.

69. When is a pessimistic cache update preferable?

A pessimistic update waits for the server response before changing cached data. It is useful when the server determines important values, the action is difficult to reverse or showing an unconfirmed result would mislead the user. onQueryStarted can await queryFulfilled and then update an existing cache entry or upsert an appropriate result.

For an approval that assigns a server-generated reference and status, I would show progress, then apply the authoritative response. This adds visible latency but avoids pretending the approval succeeded before confirmation. The response still needs to be applied to every relevant representation or followed by invalidation; updating one detail entry does not automatically synchronize all list caches.

70. What does selectFromResult accomplish?

selectFromResult lets a query consumer select the portion of its result that it needs, reducing updates when unrelated result fields change. Its returned values must have stable references where possible because shallow comparison is used to determine whether the selected result changed.

A table row can select one entity from a shared query result instead of receiving the entire list. Returning a newly created empty array on every call undermines that stability; use a stable fallback where appropriate. This optimization should follow a real rendering boundary, and it does not normalize the server response globally or change the underlying query's cache identity.

71. How do skip and skipToken prevent an unwanted query?

They allow a query to remain unstarted until required input is available. The skip option conditionally disables a query hook, while skipToken can be passed as the argument and is especially useful when TypeScript would otherwise reject an undefined argument for a required parameter.

For a detail view awaiting selection, pass the selected ID when present and skipToken otherwise. I would avoid sending a fake ID such as zero merely to satisfy the type checker, because zero may be a valid resource or create misleading errors. The component should represent the unselected state separately from loading and failure so the user sees why no request has started.

72. How do data and currentData differ in a query hook?

The data field can retain the latest available successful result associated with the hook, including a previous argument while a new argument is loading. currentData is scoped to the current argument. This distinction matters when a UI must not show an old record under a newly selected record's heading.

For a product detail screen switching IDs, I would decide whether retaining prior content is acceptable and label any transition clearly. currentData is often useful when old content would be confusing. Loading indicators also differ: isLoading describes the initial load without data, while isFetching can be true during later requests when usable data already exists.

Field

Meaning

Example

data

Latest available successful result for the hook

May retain a previous argument’s result during a switch

currentData

Successful result for the current argument

Useful when old-record content would be misleading

isLoading

Initial request without available data

Initial loading presentation

isFetching

A request is in flight

Can coexist with previously available data

73. How should polling be configured and evaluated?

A query subscription can specify a pollingInterval to refresh data periodically. The interval should reflect the required freshness and server cost, with options such as skipping polling while unfocused where appropriate. Polling is not a guarantee that data changes will appear at an exact real-time deadline.

For a background job status screen, I would poll while the job is active and stop or reduce polling after completion. Multiple consumers and lifecycle changes should be tested to avoid unexpected traffic. If updates are frequent or latency requirements are tighter, streaming may be a better fit, but it introduces its own connection, ordering and recovery responsibilities.

74. What is needed for refetching on focus or reconnect?

Configure refetchOnFocus or refetchOnReconnect as appropriate and initialize setupListeners with the store's dispatch in a compatible environment. The listener setup supplies the browser events that drive those behaviors. These settings provide opportunities to refresh subscribed data after a user returns or connectivity changes.

I would not interpret a reconnect event as proof that every service is healthy or that a previously timed-out write failed. A dashboard can refresh its reads on return while still handling request errors normally. Tests should distinguish browser event wiring from endpoint logic, and nonbrowser environments may need custom event handling rather than assuming window-based listeners exist.

75. When should transformResponse be used?

Use transformResponse to adapt a successful endpoint response into the cache shape that consumers should see, such as extracting a nested data field or normalizing a collection within that entry. It centralizes a deterministic adaptation instead of making every component understand the transport envelope.

If an API returns records alongside pagination metadata, preserve the metadata the UI actually needs rather than discarding it for convenience. Transformation is not a substitute for validating untrusted responses or for global entity deduplication across endpoints. I would keep errors and transport diagnostics in their appropriate paths and test the transformation against empty, partial and structurally invalid responses according to the endpoint contract.

76. What cache decisions matter for paginated data?

Decide how page identity, filters, ordering and membership changes map to cache entries. Separate page arguments usually produce separate entries; infinite-query features offer a different page-management model when appropriate. Mutations can affect pages where the changed record is not currently visible, so invalidation must consider the collection, not only displayed entity IDs.

For a deletion on page one, subsequent records may shift between pages. I would use a collection-level invalidation strategy or explicitly reconcile that shift rather than removing one visible row and assuming every page remains correct. Cursor-based APIs also need a clear reset policy when filters change, because an old cursor may no longer describe a valid continuation.

77. Does RTK Query create a single normalized cache for every entity?

No. RTK Query stores results by query cache key and does not automatically merge every occurrence of an entity across different endpoints into one global normalized record. A detail response and a list response can each contain their own representation of the same entity.

I would use tags to coordinate freshness, or deliberately update each relevant entry when manual synchronization is justified. createEntityAdapter can normalize one response's shape without changing this overall cache model. Understanding that boundary prevents a common bug: updating a detail entry and expecting an unrelated cached list to change automatically because both contain the same ID.

78. How should query caches be handled when a user logs out?

Clear sensitive client state according to the application's session boundary, commonly including the API's resetApiState action and appropriate slice resets. Also stop or unmount session-specific consumers and ensure new requests use the correct authentication context. Cache clearing alone is not server-side session revocation.

I would test logout followed immediately by login as a different user, including in-flight reads and persisted state. A tenant or user transition must not briefly expose the previous account's data. The correct design combines server authorization, request credentials, component lifecycle and cache ownership; hiding the screen without addressing those layers leaves stale information and race conditions unresolved.

79. How do you prevent RTK Query state and subscriptions from leaking between tests?

Create a fresh store for each test, unmount rendered consumers and clean up external mocks or listeners. When deliberately reusing a store, resetApiState can clear the API cache, but it is not a replacement for unmounting consumers or disposing resources created outside the store. An active consumer can initiate work again after a reset.

I would make cleanup part of the test harness and assert that a later test cannot pass because an earlier test left successful data cached. Polling timers, stream connections and pending mocked responses deserve explicit teardown. A useful isolation check runs the relevant test alone and in a different order; a test that succeeds only after another one may be relying on leaked state rather than correct feature behavior.

80. How would you migrate a legacy Redux application incrementally?

Start with configureStore while preserving existing reducers and required middleware, then migrate selected reducer logic to createSlice and improve selectors or async handling where the benefits are clear. Redux Toolkit works with ordinary Redux concepts, so a complete rewrite is not required merely to adopt it.

I would inventory custom middleware return behavior, persistence, action contracts and tests before changing them. Migrate one feature with regression coverage, compare behavior and then repeat. Converting syntax without addressing duplicated state or unclear domain events may reduce boilerplate while leaving the real complexity intact; architecture changes should have their own evidence and review rather than being hidden inside mechanical modernization.

Redux Interview Questions and Answers for Experienced

These answers emphasize explicit invariants, ownership and recovery strategies when several features or external systems interact.

81. How would you choose slice boundaries in a large application?

Choose boundaries around coherent domain ownership and update rules rather than mirroring every screen or API response. A slice should own facts whose transitions belong together, while selectors expose the views consumers need. Screen-based duplication often makes a shared entity disagree with itself across routes.

For an operations application, orders, users and editor workflow may have different lifecycles even if one page displays all three. I would document which feature owns each fact and which shared events can affect several slices. Avoid both extremes: one giant slice creates broad coupling, while tiny slices for every field make coordinated transitions unnecessarily difficult to understand and test.

82. How can state-machine thinking improve Redux state design?

Model valid states and transitions explicitly so impossible combinations are harder to represent. A single status field or a discriminated union can be clearer than unrelated booleans such as loading, succeeded and failed that may all become true. Reducers then enforce which events are valid in the current state.

For an approval workflow, distinguish editing, submitting, approved and rejected, with the data each state requires. A submit event should not silently erase a completed approval or permit an invalid transition. I would test forbidden transitions as well as successful ones and keep server authority clear: a client state machine can prevent UI mistakes but cannot enforce authorization on the server.

83. When should actions describe events rather than setters?

Prefer meaningful events when they express a domain transition that several consumers need to interpret. An orderSubmitted event explains what happened, while a series of setStatus, setTotal and setSelection calls exposes implementation details and can leave intermediate combinations visible. Simple local assignments can still have straightforward setter-style actions when that is the actual contract.

I would review whether a caller must know too much about a slice's internals to complete one business operation. Moving the rule into a reducer and dispatching one descriptive event can reduce that coupling. Event names alone are insufficient, however: payloads, ownership and transition validation must support the same meaning, or the design merely renames a collection of arbitrary setters.

84. How would you implement undo and redo?

Maintain a bounded history of relevant state, commonly past, present and future, or use a domain-specific command or patch history. A new edit after undo usually clears the redo branch. The scope should include reversible client edits and exclude unrelated data whose history has different semantics.

For a document editor, group keystrokes into meaningful operations and limit memory use. Undoing a local change does not automatically reverse a server mutation, payment or external notification; those need explicit compensating operations and authorization. I would test grouped edits, branch changes, no-op actions and history limits, and decide whether remote updates invalidate or rebase the local undo history.

85. What risks arise when persisting Redux state across application versions?

Persisted data can outlive the code and schema that created it. Define versioned migrations, validate restored data and provide a safe fallback when migration fails. Persist only appropriate durable state; request status, transient errors and sensitive data often should not survive a restart.

For a renamed field or changed entity shape, I would migrate a representative old snapshot and test the resulting selectors and reducers. Rehydration timing also matters because components may otherwise act on defaults before restoration finishes. Persistence is not a backup or security boundary: browser storage can be unavailable, cleared or accessed by compromised client code, so the server must remain authoritative for protected facts.

86. How would you synchronize state across browser tabs?

Define which events or facts should cross tab boundaries, then use an external channel such as BroadcastChannel with explicit origin, identity and conflict rules. Do not blindly redispatch every observed action, because that can create loops and spread irrelevant transient state. The Redux store remains local to each tab unless synchronization is deliberately added.

For logout, a small session-ended signal can cause each tab to clear its own session state. Collaborative edits are harder: timestamps alone may not resolve concurrent changes correctly, and the server may need to arbitrate. I would test duplicate messages, closed tabs and reconnect behavior and avoid broadcasting secrets or assuming every tab runs the same application version indefinitely.

87. Why should server-rendered requests avoid sharing one global store?

A module-level store reused across server requests can mix state between users and requests. Create a store per request or per appropriate rendering context so request-specific data remains isolated. The browser can then have its own store instance for that client's application lifecycle.

I would test concurrent requests for different users and confirm that one request's preloaded state never appears in another response. Shared server caches require their own authorization and keying rules; putting them into a Redux singleton does not make them safe. Framework lifecycle details matter, so the store factory and provider placement should follow the chosen rendering architecture rather than a client-only tutorial copied unchanged.

88. How do you avoid hydration mismatches with Redux state?

Ensure that the initial client render uses state consistent with the server-rendered output, and serialize any transferred state safely. Nondeterministic initial values, browser-only reads and different server/client defaults can cause the markup and selected data to disagree during hydration.

For a server-rendered preference, I would decide whether it comes from request data or must wait for a client-side effect. Avoid reading localStorage during server rendering or embedding raw unescaped JSON into HTML. Tests should include actual server rendering and client hydration when that behavior matters; passing reducer tests alone does not prove that the rendered application hydrates correctly.

89. How should Redux be used with React Server Components?

React Server Components should not read from or write to a shared Redux store as if they were client components. Keep Redux providers and hook usage in appropriate client components, and pass needed serializable data across the server/client boundary according to the framework's model. Server data fetching may already have framework-level mechanisms that do not require Redux.

I would use Redux for client interaction state that genuinely benefits from it and create stores with the required isolation. A client provider can initialize relevant data deliberately, but route changes and retained layouts need clear reset rules. The phrase server component does not remove authorization or caching obligations; those remain server responsibilities independent of the client's state container.

90. What should be considered when injecting reducers dynamically?

Dynamic reducer loading must define how reducers are registered, how initial state becomes available and how selectors behave before a feature is loaded. Redux offers replaceReducer, and Redux Toolkit provides composition tools such as combineSlices for supported injection patterns. Choose one coherent approach rather than layering competing registries.

For a lazy feature, I would load its reducer before dispatching feature actions and test selectors during the transition. Removing a feature also raises a state-retention decision: keeping its data may help navigation but consume memory or retain sensitive information. Hot replacement, duplicate registrations and persisted state need explicit handling; code splitting alone does not answer these lifecycle questions.

91. How does endpoint injection help code splitting with RTK Query?

injectEndpoints allows feature modules to add endpoint definitions to an existing API service, supporting code splitting while sharing its reducer, middleware and cache relationships. It avoids creating an unrelated API slice merely because an endpoint lives in another file. The injected API value also carries the relevant type information for its endpoints.

I would establish one base API for a coherent service boundary and let feature modules export their generated hooks after injection. Endpoint-name collisions must be intentional and governed by the override behavior. Tests should load features in realistic orders so an endpoint is not used before its module registers it, and the application's store should mount the base API once.

92. When are multiple RTK Query API slices justified?

Separate API slices can be appropriate for genuinely separate service boundaries or configurations, but they create separate caches, middleware and tag-invalidation domains. Tags in one API slice do not automatically invalidate entries in another. Creating one slice per file can therefore make coordination harder and add middleware overhead.

I would start from service ownership, authentication and lifecycle needs, then use endpoint injection for modularity within a shared API. If two services affect the same screen, cross-service refresh must be explicit. A single API slice is not a universal rule either: independent backends with different request behavior may justify separation when the resulting coordination is understood and tested.

93. How can streaming updates be integrated into an RTK Query cache entry?

Use an endpoint lifecycle such as onCacheEntryAdded to coordinate a stream with the cache entry's lifetime. Wait for initial data when needed, apply incoming updates through updateCachedData and clean up the connection when cacheEntryRemoved resolves. Handle failures and the possibility that the entry disappears before initialization completes.

For a live task feed, validate message shape and apply ordered updates by stable ID. A WebSocket connection by itself does not guarantee completeness: reconnects can miss messages, so sequence numbers or a fresh snapshot may be necessary. I would keep connection resources outside serializable cache data and test cleanup so navigation does not leave abandoned streams running.

94. Why can overlapping optimistic updates make rollback unsafe?

Each optimistic patch is calculated against a particular cache state. If several operations overlap, undoing an earlier failed patch can restore values that overwrite a later successful update. A simple patch undo is therefore not automatically a correct conflict-resolution strategy.

For rapid edits to one record, I would consider serializing writes, associating operations with versions or invalidating and refetching after failure. The appropriate choice depends on latency and conflict requirements. Tests should force reverse-order success and failure, not only one optimistic mutation at a time, and the interface should explain any reconciliation that changes a value the user believed was saved.

95. How should a client handle a timed-out write that may have succeeded?

Treat the outcome as uncertain rather than assuming failure. Use a server-supported operation identifier or idempotency key where available, and reconcile the result before retrying a side-effecting operation. Redux can represent pending, confirmed and uncertain states, but it cannot create server-side idempotency by itself.

For an order submission, I would preserve the operation identity, query its status or retry according to the server's documented idempotency contract. Generating a new key for every retry can create duplicate operations. A strong design also distinguishes a network timeout from a confirmed rejection so the UI does not invite a user to repeat a potentially completed purchase as if nothing happened.

Observed result

What is known

Safe next step

Confirmed server rejection

The operation was rejected under the stated contract

Correct the input or authority problem

Timeout after submission

Completion may be unknown

Reconcile using operation identity

Confirmed success

The operation completed as reported

Update relevant views from the authoritative result

96. How do you reconcile temporary IDs after an optimistic creation?

Give the optimistic record a distinct temporary identity and replace or map it to the server's authoritative ID when creation succeeds. Update relationships and selections that referenced the temporary ID, and define what happens if the operation fails or is retried. The temporary identifier must not accidentally collide with real IDs.

For a new task and its comments, I would avoid sending dependent writes with a temporary ID unless the API explicitly supports that protocol. Reconciliation may need one coordinated action so the entity map, ordered IDs and current selection remain consistent. Tests should cover multiple simultaneous creations and a response arriving after the user has left the editing screen.

97. How would you prevent several expired requests from all refreshing a token?

Coordinate refresh through a shared in-flight refresh promise or mutex in the request layer. One request performs refresh while others wait, then retry with the updated credentials if refresh succeeds. On failure, transition to an appropriate session-ended state and avoid an infinite refresh loop.

With RTK Query, this can be implemented in a custom baseQuery wrapper using a carefully scoped coordinator. I would exclude the refresh request itself from recursive refresh handling and account for logout while waiters are pending. Server authorization remains decisive, and tokens should not be exposed in action logs or persisted merely because the client needs to attach credentials to requests.

98. What contract must a custom RTK Query baseQuery follow?

A baseQuery receives the endpoint argument, API utilities and extra options, then returns a result containing data on success or error on failure. It can be asynchronous, but expected failures should be caught and converted into that result contract rather than escaping as unhandled exceptions. The error shape should suit the application and be handled consistently by consumers.

For a wrapper around an HTTP client, I would map a successful response into { data: response.data } and catch client failures into a defined { error: ... } value. Respect api.signal where the underlying client supports cancellation and preserve useful metadata deliberately. A transport wrapper should not pretend that every failure has an HTTP status: connection failures, cancellation and invalid response handling may require different representations.

99. How do selector cache lifetime and memory use affect architecture?

A selector's memoization strategy determines which argument combinations and results remain reusable and potentially retained. Match selector lifetime to its consumers and inspect actual memoizer behavior rather than assuming all caches are single-entry or unbounded. Large parameter spaces can make a seemingly small optimization retain substantial data.

For a dashboard with many temporary filters, I would measure recomputations and memory as filters change and components unmount. A per-component selector can provide isolation but multiplies caches; a shared selector can improve reuse but retain a broader working set. Choose based on observed access patterns and avoid using memoization as a substitute for a sensible state shape.

100. Why might a selector need to be draft-safe inside an Immer reducer?

An Immer draft is a proxy whose apparent object identity can remain stable while its fields change during one producer execution. An ordinary memoized selector may therefore reuse an outdated result if called repeatedly with that draft. createDraftSafeSelector detects the draft situation and favors recomputation so the result reflects current draft values.

I would generally keep derivation outside reducers, but some reducer logic legitimately needs a computed view while applying a transition. In that case, use an appropriate draft-safe selector and test a call before and after a draft change. Entity-adapter selectors are draft-safe by default. Draft safety addresses this specific Immer interaction; it does not make an impure selector acceptable or remove the need to understand its dependencies.

101. Does batching make several dispatched actions one atomic transaction?

No. Rendering or notification batching can reduce how often subscribers or React render work run, but reducers still process actions according to their dispatch semantics. Code reading the store between dispatches can observe intermediate state. Redux Toolkit's auto-batching behavior also depends on the actions and configuration involved.

If an invariant must hold as one state transition, I would model one action that updates the relevant state together rather than rely on batching to hide inconsistent steps. Batching is a performance mechanism, not a database transaction or rollback system. Tests should assert the domain invariant directly and avoid inferring atomicity merely because the screen rendered once.

102. How do listener cancellation and task coordination work in practice?

Listener middleware supports cancellation-aware helpers and task coordination, but cancellation must be connected to the work being performed. cancelActiveListeners can cancel other active instances of the same listener, and cancellation-aware delays or waits can stop their workflow. An arbitrary external promise does not become cancellable automatically.

For debounced search persistence, I would cancel older listener instances, wait using the listener API and then perform the latest operation. If a network request has begun, pass or bridge an appropriate abort signal where supported and still guard against stale completion. A catch handler should distinguish cancellation from actual failure so expected supersession does not flood error reporting.

103. What limitation applies to getOriginalState in listener middleware?

getOriginalState exposes the state before the triggering reducer execution, but it must be called synchronously within the listener's initial execution. Keeping unrestricted access after asynchronous work would retain old state longer, so calling it later is not supported. Capture only the needed values before awaiting.

For a listener that compares the previous and new preference, read the old preference immediately, then use the current state or captured values according to the intended workflow. Do not capture the entire old store casually for a long-lived task. A test that inserts an asynchronous boundary can reveal code that worked synchronously but incorrectly assumed the original-state accessor remained valid indefinitely.

import { configureStore, createListenerMiddleware, createSlice }
  from '@reduxjs/toolkit';
const counter = createSlice({
  name: 'counter', initialState: 0,
  reducers: { increment: (state) => state + 1 }
});
const listener = createListenerMiddleware();
listener.startListening({
  actionCreator: counter.actions.increment,
  effect: async (_action, api) => {
    const previous = api.getOriginalState().counter; // Before await.
    await api.delay(1);
    console.assert(typeof previous === 'number');
  }
});
const store = configureStore({
  reducer: { counter: counter.reducer },
  middleware: (defaults) => defaults().prepend(listener.middleware)
});
store.dispatch(counter.actions.increment());
import { configureStore, createListenerMiddleware, createSlice }
  from '@reduxjs/toolkit';
const counter = createSlice({
  name: 'counter', initialState: 0,
  reducers: { increment: (state) => state + 1 }
});
const listener = createListenerMiddleware();
listener.startListening({
  actionCreator: counter.actions.increment,
  effect: async (_action, api) => {
    const previous = api.getOriginalState().counter; // Before await.
    await api.delay(1);
    console.assert(typeof previous === 'number');
  }
});
const store = configureStore({
  reducer: { counter: counter.reducer },
  middleware: (defaults) => defaults().prepend(listener.middleware)
});
store.dispatch(counter.actions.increment());
import { configureStore, createListenerMiddleware, createSlice }
  from '@reduxjs/toolkit';
const counter = createSlice({
  name: 'counter', initialState: 0,
  reducers: { increment: (state) => state + 1 }
});
const listener = createListenerMiddleware();
listener.startListening({
  actionCreator: counter.actions.increment,
  effect: async (_action, api) => {
    const previous = api.getOriginalState().counter; // Before await.
    await api.delay(1);
    console.assert(typeof previous === 'number');
  }
});
const store = configureStore({
  reducer: { counter: counter.reducer },
  middleware: (defaults) => defaults().prepend(listener.middleware)
});
store.dispatch(counter.actions.increment());

104. How can custom asynchronous middleware break dispatch callers?

Middleware controls the value returned by dispatch. Declaring middleware's action handler async or failing to return next(action) can wrap, replace or discard the downstream return value. Callers may then lose a thunk's abort method or receive a different promise contract than expected.

I would keep ordinary pass-through middleware synchronous and launch separate asynchronous work deliberately unless changing dispatch's contract is intentional. A regression test should dispatch a thunk and verify the returned capabilities, not only the eventual state. Middleware order also affects this behavior, so testing the complete configured chain is more useful than testing one middleware function in isolation.

105. How should Redux DevTools and action logging handle sensitive data?

Avoid placing secrets or unnecessary personal data into state and actions in the first place. Configure logging and DevTools exposure according to the environment, and use sanitization where appropriate, while recognizing that sanitizers do not remove sensitive values from the actual store. Client code and browser storage are not trusted secret vaults.

I would review authentication payloads, error responses and customer records for accidental exposure in screenshots, remote debugging or persisted logs. Disabling DevTools in production can reduce one exposure route but does not fix an overly sensitive state model. Security review should examine the full data lifecycle and server authorization rather than treating one configuration flag as sufficient protection.

106. How would you design an offline mutation queue?

Represent queued operations with stable identities, explicit status and enough domain information to replay them safely. Define ordering, dependencies, retry policy, conflict handling and authentication changes. Persisting an array of requests is only the beginning; the server must support the semantics required for safe retries and reconciliation.

For offline task edits, independent changes may be replayable while a delete followed by an edit requires a deliberate rule. I would distinguish retryable transport failures from permanent validation failures and surface conflicts to the user. Logout or account switching must not replay one user's queue under another identity, and tests should simulate partial replay followed by another interruption.

107. Where should sockets, timers and other resource handles live?

Keep resource handles in a lifecycle-managed layer outside ordinary serializable Redux state, such as middleware, a service or an appropriate component effect. Store the meaningful status or identifier that the application needs to render and reason about. A socket object in the store does not become replayable just because a warning is disabled.

For a connection, state might contain connecting, connected or failed plus a safe error description, while the service owns opening and closing the socket. I would define cleanup on logout and feature teardown and test that duplicate initialization does not leak resources. Ownership should be explicit so reducers never need to call methods on a live external object.

108. How would you implement a global reset without erasing everything indiscriminately?

Define the reset boundary and apply it deliberately through shared events or root-reducer logic. Passing undefined to selected reducer state can reinitialize it, while other state may be preserved according to policy. A reset should be a documented domain operation, not an accidental consequence of replacing arbitrary objects.

For logout, account-specific data and API caches should clear, while a nonsensitive display preference may remain. Persisted storage, in-flight requests and mounted query consumers need corresponding lifecycle handling so cleared data does not immediately reappear. I would test the complete session transition, including a rapid second login, instead of checking only that the root object looked empty immediately after dispatch.

109. How do you test debounced or delayed Redux workflows reliably?

Control time with the test framework's fake timers where appropriate, and explicitly flush the asynchronous work triggered by advancing time. Assert the observable workflow: which operation eventually occurs, which earlier task is cancelled and how errors are handled. Avoid real sleeps that make tests slow and timing-dependent.

For a debounced listener, dispatch several changes, advance to just before the threshold and confirm no persistence, then cross it and confirm only the intended latest value is saved. Timer advancement alone may not settle promise microtasks, so the test must follow the framework's supported async utilities. Restore timers and clean up listeners between tests to prevent misleading cross-test failures.

110. What makes a reducer deterministic, and how would you test it?

For the same input state and action, a deterministic reducer returns an equivalent next state without depending on external time, randomness or mutable services. Generate such external values before dispatch and include them in the action. Immutability and determinism are related but distinct: copying objects does not make an external clock read deterministic.

I would freeze representative inputs where useful, run the same transition repeatedly and assert that previous snapshots remain unchanged. Domain invariants, boundary cases and unknown actions matter more than snapshots of every internal property. Property-based tests can be useful for complex transition rules, but they should encode meaningful invariants rather than simply duplicate the reducer's implementation.

111. How would you investigate slow updates in a very large collection?

Measure where time is spent: reducer work, selector recomputation, component rendering or browser layout. Normalization, focused subscriptions and list virtualization address different parts of the problem. Replacing Redux or adding memoization without locating the cost can increase complexity without improving the user experience.

For a single-row edit in a large table, I would inspect whether the reducer rebuilds every entity and whether each row selects the whole list. Preserve unchanged references, derive only what is necessary and virtualize when the DOM itself is the bottleneck. Benchmark realistic data sizes and interactions; a tiny isolated reducer benchmark does not represent a screen with thousands of rendered cells.

112. Where should search debouncing and request freshness rules live?

Separate the immediate input value from the timing of remote work. Debouncing can live in an appropriate component or side-effect layer, while query arguments and request identity determine which result is current. Delaying every input-state update can make typing feel unresponsive without actually solving stale-result races.

I would update the visible input immediately, derive or emit a debounced search term and ensure results correspond to that term. Cancellation can reduce unnecessary requests, but the display should still guard against old results and represent empty searches clearly. Test fast typing, clearing the field and route changes so a delayed operation does not resurrect a search the user already abandoned.

113. How should a Redux-backed UI handle out-of-order stream events?

Use a protocol-level ordering or version mechanism and apply updates only when they fit the current entity or stream version. Arrival order alone is insufficient when reconnects, retries or several producers are involved. The client also needs a recovery strategy for gaps, duplicates and unsupported versions.

For a task stream, an event sequence can identify a missing update and trigger a fresh snapshot before incremental processing resumes. Ignoring every older event may be correct for full replacements but wrong for additive operations, so the protocol's semantics matter. Redux makes the resulting state transitions inspectable; it does not supply message delivery or conflict resolution guarantees on behalf of the transport.

114. How would you investigate excessive RTK Query cache memory?

Inspect the number of distinct cache keys, response sizes, retention settings and active subscriptions. A frequently changing argument can create many entries, while an unexpectedly mounted consumer can prevent an entry from becoming unused. Cache retention is only one factor and should not be changed blindly.

For a search screen, I would check whether every keystroke becomes a separate long-lived query and whether large responses can be reduced or paginated. Manual cache-key collapsing can reduce entries but risks mixing semantically different results. Measure memory and network trade-offs together, then test navigation and account changes to confirm that the chosen lifecycle preserves both freshness and data isolation.

115. How would you approach a Redux ecosystem upgrade?

Review the official migration notes for Redux, Redux Toolkit, React-Redux and related selector tooling, then identify changes that affect the application's actual APIs, types and runtime assumptions. Upgrade with a lockfile and focused regression tests rather than assuming a compatible-looking import means behavior is unchanged.

I would pay particular attention to custom middleware typing, action assumptions, selector memoization and SSR integration. Stage the upgrade so failures can be traced to a manageable change, and remove temporary compatibility code once it is no longer needed. Do not promise that all historical code patterns are current best practice; explain which behavior is version-dependent and verify it against the installed versions.

116. Why can React Strict Mode expose duplicate-request or cleanup bugs?

Development Strict Mode can rerun relevant render and effect setup/cleanup paths to reveal unsafe side effects and missing cleanup. Code that assumes an effect will execute exactly once may issue duplicate work or leak resources. The solution is to make the lifecycle correct, not simply suppress the diagnostic mode.

I would examine whether fetching belongs in a query subscription, whether an effect returns cleanup and whether writes are incorrectly triggered merely by mounting. Server-side idempotency may still be necessary for side-effecting operations. Test the intended production behavior as well as development checks, and avoid claiming that Strict Mode means every event handler or reducer is arbitrarily dispatched twice.

117. Why should components avoid dispatching during render?

Render should calculate UI from the current inputs without causing state-changing side effects. Dispatching during render can trigger repeated updates, warnings or behavior that depends on React's rendering schedule. Put user-triggered dispatches in event handlers and lifecycle synchronization in an appropriate effect or external workflow.

If a component dispatches because selected data looks incomplete, I would first ask whether the value should be derived or initialized at a better boundary. Moving the same unconditional dispatch into an effect can still create a loop if its dependencies change on every update. The correct fix defines when the transition should occur and ensures it is not repeated merely because rendering happened again.

118. Can Redux action history serve as a reliable business audit log?

Not by itself. Client-side action history is useful for debugging, but it can be incomplete, altered, cleared or disconnected from what the server actually accepted. A business audit trail needs authoritative recording, access controls, integrity, retention and meaningful identities at the appropriate trusted boundary.

For an approval workflow, an approvalRequested action proves only that the client expressed an intent. The server's confirmed decision and audit record establish the authoritative outcome. I would correlate client diagnostics with server operation IDs while minimizing sensitive data, and avoid promising compliance or nonrepudiation merely because Redux DevTools can replay a sequence of local actions.

119. When might multiple Redux stores be appropriate?

Most applications benefit from one store for their coordinated Redux state, but independently embedded applications or isolated integration boundaries can justify separate stores. Multiple stores require deliberate provider contexts, communication rules and lifecycle management. They do not automatically provide security isolation within the same JavaScript environment.

For two independent widgets on a host page, each may own its own store without sharing domain state. If features repeatedly synchronize the same facts across stores, that is a signal to reconsider the boundary. I would test provider placement and shared dependencies carefully so a component does not accidentally read from the wrong store or dispatch an action into an unrelated instance.

120. How would you design Redux state for a collaborative task editor?

Separate authoritative server data, local edit intent and transient UI state, then define how they reconcile. RTK Query can manage server reads and mutations, while a slice can represent an unsaved draft, selection and explicit conflict state. Use entity IDs and versions so an incoming update can be compared with the draft's starting point.

I would preserve unsaved work when a newer server version arrives, show a conflict when automatic merging is unsafe and submit with the server's concurrency contract. Optimistic updates, retries and stream events must share the same operation and version rules. Validate the design with concurrent edits, uncertain saves, reconnects and account changes; a happy-path demo does not establish that a collaborative editor protects user work.

  1. Define server entities, versions and operation identities.

  2. Separate unsaved edit intent from authoritative cached data.

  3. Specify conflict, retry and uncertain-save behavior.

  4. Test out-of-order responses, reconnects and session transitions.

Redux Documentation and Further Reading

Use these official resources for deeper study and version-specific details. Plain JavaScript fixtures were executed locally. Package-based Redux Toolkit examples were syntax-checked and reviewed against documentation, but could not be executed because the local environment could not resolve the npm registry. React rendering, hydration, real network services and production load behavior were not tested.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts