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
Why: createSlice generates both from one definition.
2Which library lets RTK reducers 'mutate' state safely?Asked almost every time
Why: Immer turns draft mutations into immutable updates.
3Which RTK API generates data-fetching hooks?Asked almost every time
Why: Endpoints become hooks such as useGetPostsQuery.
4Which function defines an RTK Query API slice?Asked almost every time
Why: It generates hooks and reducers.
5What must be added to the store for RTK Query?Asked almost every time
Why: Middleware manages caching.
6How long is unused data kept by default?Asked almost every time
Why: keepUnusedDataFor.
7Which actions does createAsyncThunk dispatch?Very often asked
Why: They follow the promise lifecycle.
8In RTK Query, what refetches a list after a mutation?Very often asked
Why: Tag invalidation triggers refetch.
9What does configureStore add by default?Very often asked
Why: Plus dev-only mutation and serializability checks.
10Where do you handle thunk lifecycle actions in a slice?Very often asked
Why: extraReducers responds to external actions.
11Which option sets auth headers?Very often asked
Why: Reads the token from state.
12Which adds endpoints from feature files?Very often asked
Why: Code-split endpoints.
13Which option refetches a query on an interval?Very often asked
Why: Pass it to the hook.
14Which reshapes data before it is cached?Very often asked
Why: Runs on successful responses.
15What does unwrap() on a mutation do?Very often asked
Why: Returns the payload or throws.
16Which helper manages normalised { ids, entities } state?Often asked
Why: Entity adapters give CRUD reducers and selectors.
17In an Immer reducer you should…Often asked
Why: Doing both throws an error.
18How do you return a custom error from a thunk?Often asked
Why: rejectWithValue sets the rejected payload.
19Which RTK utility updates cached query data for an optimistic update?Often asked
Why: It patches the cache and returns an undo handle.
20Which builder method handles actions matching a condition?Often asked
Why: e.g. isPending.
21Which helper generates unique IDs in prepare callbacks?Often asked
Why: Exported by RTK.
22Which call resets RTK Query state in tests?Often asked
Why: Clears cache between tests.
23Which call enables refetchOnFocus behaviour?Often asked
Why: Required for focus and reconnect refetching.
24Which selector is safe inside Immer reducers?Often asked
Why: Handles drafts.
25Which tool generates endpoints from OpenAPI?Often asked
Why: Keeps types in sync.
26The listener middleware is mainly for…Sometimes asked
Why: It reacts to actions or state changes.
27RTK 2's combineSlices supports…Sometimes asked
Why: Slices can be injected for code splitting.
28What action type does createSlice({ name: 'todos', reducers: { added } }) generate?Sometimes asked
Why: Types are name/reducerName.
29Which actions must redux-persist ignore in the serialisability check?Sometimes asked
Why: They carry functions.
30Which hook option picks part of a query result?Sometimes asked
Why: Reduces re-renders.
Track what you have practised and search every bank in your dashboard.
Start learning