Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Interview questions with answers

Redux Toolkit interview questions and answers

configureStore, createSlice, Immer, thunks and RTK Query. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.

Subjective
30
Objective
30

Subjective questions 30

1What problems does Redux Toolkit solve?Asked almost every time

Classic Redux needed lots of boilerplate (action types, action creators, switch reducers, immutable spread updates, store and middleware setup) and was easy to get wrong. RTK is the official toolset: configureStore with good defaults and DevTools, createSlice generating actions and reducers, Immer for safe 'mutating' updates, createAsyncThunk, entity adapters and RTK Query for data fetching.

2Explain createSlice.Asked almost every time

createSlice({ name, initialState, reducers }) creates a slice reducer and matching action creators from one object. Reducer functions may mutate a draft state thanks to Immer, and action types are generated as name/reducerName. extraReducers with a builder handles actions defined elsewhere, such as thunk lifecycle actions.

3What is RTK Query and when would you use it?Asked almost every time

A data fetching and caching layer built into RTK. You define an API with createApi and endpoints (queries and mutations); it generates hooks like useGetPostsQuery, caches results by arguments, deduplicates requests, tracks loading and error states, refetches on focus or reconnect, and invalidates cache with tags. Use it when your app already uses Redux and needs server data.

4How does Immer make 'mutating' code safe?Asked almost every time

Immer gives reducers a draft proxy of the state. Your changes to the draft are recorded, and Immer produces a new immutable state with structural sharing, copying only the changed paths. You must either mutate the draft or return a new value, not both.

5How do you define an RTK Query API?Asked almost every time

Call createApi({ reducerPath, baseQuery: fetchBaseQuery({ baseUrl }), tagTypes, endpoints: build => ({ getPosts: build.query(...), addPost: build.mutation(...) }) }), add api.reducer and api.middleware to the store, and use the generated hooks such as useGetPostsQuery and useAddPostMutation.

6How does RTK Query cache and deduplicate requests?Asked almost every time

Each endpoint plus its argument forms a cache key. Components using the same key share one request and cache entry, tracked by subscriptions. When the last subscriber unmounts, data stays for keepUnusedDataFor (60 seconds by default) before removal.

7How do you handle authentication tokens in RTK Query?Asked almost every time

Use prepareHeaders in fetchBaseQuery to read the token from state and set the Authorization header. For refresh, wrap the base query: on a 401, call the refresh endpoint, store the new token and retry, using a mutex so parallel requests refresh only once.

8How does createAsyncThunk work?Very often asked

It takes an action type prefix and an async payload creator, and returns a thunk that dispatches pending, then fulfilled with the returned value or rejected with the error. Reducers handle those in extraReducers. rejectWithValue returns a custom error payload, and condition can skip a call.

9How do tags and invalidation work in RTK Query?Very often asked

Queries declare providesTags (for example [{ type: 'Post', id }]), and mutations declare invalidatesTags. When a mutation succeeds, any cached query providing an invalidated tag refetches automatically, keeping lists and details in sync without manual cache code.

10What does configureStore set up for you?Very often asked

It combines slice reducers, adds the thunk middleware, turns on Redux DevTools, and in development adds checks for accidental state mutation and non-serialisable values. You can customise middleware with a callback and add enhancers.

11What is createEntityAdapter?Very often asked

It manages normalised collections stored as { ids, entities }, with prebuilt reducers (addOne, upsertMany, removeOne, setAll) and memoised selectors (selectAll, selectById), optionally sorted. It removes repetitive CRUD logic.

12How do you type RTK with TypeScript?Very often asked

Infer RootState from store.getState and AppDispatch from store.dispatch, then create pre-typed hooks with useDispatch.withTypes<AppDispatch>() and useSelector.withTypes<RootState>(). Slices infer action payload types from PayloadAction<T>.

13What are extraReducers and the builder callback?Very often asked

extraReducers: builder => builder.addCase(fetchTodos.fulfilled, (state, action) => {...}).addMatcher(isPending, ...) lets a slice respond to actions defined elsewhere (thunks, other slices) with full type inference.

14How do you code-split RTK Query endpoints?Very often asked

Create one base API with createApi and no or few endpoints, then call api.injectEndpoints({ endpoints }) from feature files, so endpoint definitions load with the feature that uses them.

15How do you poll or refetch data in RTK Query?Very often asked

Pass pollingInterval to a query hook, or refetchOnFocus and refetchOnReconnect (with setupListeners(store.dispatch)), or call refetch() from the hook result. refetchOnMountOrArgChange refetches when the component mounts.

16How do you transform API responses in RTK Query?Very often asked

Use transformResponse on an endpoint to reshape data before caching (for example normalising with an entity adapter), and transformErrorResponse for errors. Selectors with selectFromResult pick parts in components.

17How do you test code that uses RTK Query?Very often asked

Render components with a real store containing the API slice, mock the network with MSW, and assert on the UI after requests resolve. Reset the API state between tests with api.util.resetApiState().

18How do you share state between slices?Very often asked

Slices respond to each other's actions in extraReducers, thunks can read state with getState and dispatch to several slices, and selectors combine slices. Avoid importing one reducer into another.

19How do you do optimistic updates in RTK Query?Often asked

In a mutation's onQueryStarted, call dispatch(api.util.updateQueryData(...)) to patch the cached data immediately, keep the returned patch, await queryFulfilled, and call patch.undo() if it fails.

20What is the listener middleware?Often asked

A lightweight way to run side effects in response to actions or state changes (startListening({ actionCreator, effect })), with async effects, cancellation and conditions. It replaces many uses of sagas or observables.

21When would you use RTK Query vs. TanStack Query?Often asked

RTK Query fits apps already on Redux, keeping server cache in the same store and DevTools, and can generate clients from OpenAPI. TanStack Query is independent of Redux, very flexible, and widely used outside Redux apps. Both solve server-state caching.

22What does createSelector from RTK do?Often asked

RTK re-exports Reselect's createSelector, which memoises derived data so components only re-render when inputs change. createDraftSafeSelector is safe to use with Immer drafts inside reducers.

23How do you prepare action payloads?Often asked

A slice reducer can be an object with reducer and prepare functions: prepare builds the payload (adding an id or timestamp with nanoid) so callers pass simple arguments and the reducer stays pure.

24What is createListenerMiddleware good for compared with thunks?Often asked

Thunks run when you dispatch them; listeners react to actions or state changes anywhere, such as saving to localStorage when settings change, analytics, or cancelling previous work with cancelActiveListeners.

25How do you persist RTK state?Often asked

Use redux-persist with persistReducer and persistStore, ignoring its action types in the serialisability check (ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]), and avoid persisting the RTK Query cache unless needed.

26What is createAction and createReducer?Often asked

createAction('todos/added') creates a typed action creator; createReducer(initialState, builder => ...) builds a reducer with Immer. createSlice combines both, so these are used for actions shared across slices.

27How does RTK Query handle errors?Often asked

Hooks expose isError and error (an object with status and data for fetchBaseQuery). Mutations can be unwrap()ped to throw on failure in try/catch. Middleware can listen for rejected actions to show global error toasts.

28What does combineSlices do?Sometimes asked

In RTK 2, combineSlices builds a root reducer from slices and supports lazy-loading slices later with inject, useful for code splitting large apps.

29Why does RTK warn about non-serialisable values?Sometimes asked

Redux expects plain data for DevTools, persistence and time travel. Putting promises, class instances or functions in state or actions breaks those features, so the serializability middleware warns in development.

30What is RTK Query code generation?Sometimes asked

Tools like @rtk-query/codegen-openapi generate endpoints and TypeScript types from an OpenAPI spec (or GraphQL schema), keeping the client in sync with the server.

Objective questions 30

1Which function creates actions and a reducer together?Asked almost every time
  1. AcreateSliceCorrect answer
  2. BcreateAction
  3. CconfigureStore
  4. DcreateReducer

Why: createSlice generates both from one definition.

2Which library lets RTK reducers 'mutate' state safely?Asked almost every time
  1. ARxJS
  2. BLodash
  3. CImmerCorrect answer
  4. DImmutable.js

Why: Immer turns draft mutations into immutable updates.

3Which RTK API generates data-fetching hooks?Asked almost every time
  1. AcreateListenerMiddleware
  2. BcreateAsyncThunk
  3. CcreateApi (RTK Query)Correct answer
  4. DcreateSelector

Why: Endpoints become hooks such as useGetPostsQuery.

4Which function defines an RTK Query API slice?Asked almost every time
  1. AcreateSlice
  2. BcreateAsyncThunk
  3. CconfigureStore
  4. DcreateApiCorrect answer

Why: It generates hooks and reducers.

5What must be added to the store for RTK Query?Asked almost every time
  1. ANothing
  2. Bapi.reducer and api.middlewareCorrect answer
  3. COnly api.reducer
  4. DA Provider only

Why: Middleware manages caching.

6How long is unused data kept by default?Asked almost every time
  1. A5 minutes
  2. BForever
  3. C60 secondsCorrect answer
  4. D0 seconds

Why: keepUnusedDataFor.

7Which actions does createAsyncThunk dispatch?Very often asked
  1. Apending/fulfilled/rejectedCorrect answer
  2. Brequest/success
  3. Cbegin/commit
  4. Dstart/end

Why: They follow the promise lifecycle.

8In RTK Query, what refetches a list after a mutation?Very often asked
  1. AA page reload
  2. BinvalidatesTags matching providesTagsCorrect answer
  3. CsetTimeout
  4. DkeepUnusedDataFor

Why: Tag invalidation triggers refetch.

9What does configureStore add by default?Very often asked
  1. AGraphQL
  2. BSaga middleware
  3. CThunk middleware and DevToolsCorrect answer
  4. DPersistence

Why: Plus dev-only mutation and serializability checks.

10Where do you handle thunk lifecycle actions in a slice?Very often asked
  1. Areducers
  2. BextraReducersCorrect answer
  3. Cmiddleware
  4. Dselectors

Why: extraReducers responds to external actions.

11Which option sets auth headers?Very often asked
  1. AtransformRequest
  2. BheadersMiddleware
  3. CsetHeaders
  4. DprepareHeadersCorrect answer

Why: Reads the token from state.

12Which adds endpoints from feature files?Very often asked
  1. AcreateApi again
  2. Bapi.extend
  3. Capi.injectEndpointsCorrect answer
  4. Dapi.addEndpoints

Why: Code-split endpoints.

13Which option refetches a query on an interval?Very often asked
  1. ArefreshRate
  2. Binterval
  3. CrefetchEvery
  4. DpollingIntervalCorrect answer

Why: Pass it to the hook.

14Which reshapes data before it is cached?Very often asked
  1. Aprepare
  2. BextraReducers
  3. CtransformResponseCorrect answer
  4. DselectFromResult

Why: Runs on successful responses.

15What does unwrap() on a mutation do?Very often asked
  1. AReturns the store
  2. BThrows on error so you can try/catchCorrect answer
  3. CCancels the request
  4. DClears the cache

Why: Returns the payload or throws.

16Which helper manages normalised { ids, entities } state?Often asked
  1. AcombineReducers
  2. BcreateEntityAdapterCorrect answer
  3. Cnormalizr only
  4. DcreateSlice alone

Why: Entity adapters give CRUD reducers and selectors.

17In an Immer reducer you should…Often asked
  1. AAlways return undefined
  2. BMutate the draft and return a new object
  3. CMutate the draft or return a new value, not bothCorrect answer
  4. DNever change state

Why: Doing both throws an error.

18How do you return a custom error from a thunk?Often asked
  1. Areturn null
  2. Bthrow new Error only
  3. CrejectWithValue(payload)Correct answer
  4. Ddispatch(error)

Why: rejectWithValue sets the rejected payload.

19Which RTK utility updates cached query data for an optimistic update?Often asked
  1. Aapi.util.updateQueryDataCorrect answer
  2. Bstore.replace
  3. Capi.patch
  4. DsetQueryData

Why: It patches the cache and returns an undo handle.

20Which builder method handles actions matching a condition?Often asked
  1. AaddMatcherCorrect answer
  2. BaddCase only
  3. CaddDefault
  4. DaddFilter

Why: e.g. isPending.

21Which helper generates unique IDs in prepare callbacks?Often asked
  1. AMath.random
  2. BDate.now
  3. CnanoidCorrect answer
  4. Duuidv4 only

Why: Exported by RTK.

22Which call resets RTK Query state in tests?Often asked
  1. Ajest.reset()
  2. Bapi.util.resetApiState()Correct answer
  3. Cstore.clear()
  4. Dapi.reset()

Why: Clears cache between tests.

23Which call enables refetchOnFocus behaviour?Often asked
  1. AsetupListeners(store.dispatch)Correct answer
  2. BenableFocus()
  3. Capi.listen()
  4. Dwindow.focus()

Why: Required for focus and reconnect refetching.

24Which selector is safe inside Immer reducers?Often asked
  1. AuseSelector
  2. Bselect
  3. CcreateDraftSafeSelectorCorrect answer
  4. DcreateSelector only

Why: Handles drafts.

25Which tool generates endpoints from OpenAPI?Often asked
  1. Aopenapi-fetch
  2. B@rtk-query/codegen-openapiCorrect answer
  3. Cswagger-ui
  4. Dgraphql-codegen only

Why: Keeps types in sync.

26The listener middleware is mainly for…Sometimes asked
  1. ARunning side effects in response to actionsCorrect answer
  2. BStyling
  3. CPersisting state
  4. DRouting

Why: It reacts to actions or state changes.

27RTK 2's combineSlices supports…Sometimes asked
  1. ASSR only
  2. BLazy-injecting slices laterCorrect answer
  3. CGraphQL
  4. DWeb workers

Why: Slices can be injected for code splitting.

28What action type does createSlice({ name: 'todos', reducers: { added } }) generate?Sometimes asked
  1. AADDED
  2. Btodos/addedCorrect answer
  3. Cadded/todos
  4. Dtodos.ADDED

Why: Types are name/reducerName.

29Which actions must redux-persist ignore in the serialisability check?Sometimes asked
  1. AThunks
  2. BNone
  3. CIts own lifecycle actions like REHYDRATECorrect answer
  4. DAll actions

Why: They carry functions.

30Which hook option picks part of a query result?Sometimes asked
  1. AtransformResponse
  2. BselectFromResultCorrect answer
  3. Cselect
  4. Dpick

Why: Reduces re-renders.

Track what you have practised and search every bank in your dashboard.

Start learning