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

Technology handbook

Redux Toolkit

Modern Redux setup, slices, async thunks, entity adapters, listeners and RTK Query.

Topics
37
Sections
5

Hooks

Generated endpoint hooks

createApi turns every endpoint into its own typed query or mutation hook.

  • Use the React-specific RTK Query entry point for generated hooks.
  • Query hooks subscribe to endpoint-and-argument cache entries.
  • Mutation hooks return a trigger and request status.

useQuery options

skip, pollingInterval and refetchOnMountOrArgChange are decided per call site, not per endpoint.

  • skip controls whether the hook subscribes and fetches.
  • pollingInterval schedules refreshes while subscribed.
  • Refetch options control reuse of an existing cached result.

useLazyQuery

Trigger a query from an event rather than on render, and keep the last result.

  • Call the lazy trigger when the initiating event occurs.
  • Await its result when subsequent work depends on the response.
  • Handle loading and failure states for the triggered argument.

useMutation

Take the trigger function and the request state as one tuple, and reset it deliberately.

  • Call the trigger with the mutation's argument payload.
  • Use unwrap to handle success and failure with ordinary promises.
  • Reset displayed mutation state when its UI flow ends.

usePrefetch

Warm the cache on hover or route entry before the user asks for the data.

  • Trigger prefetch for a likely upcoming query argument.
  • Use age or force options to control cache warming.
  • Prefetching alone does not create a lasting component subscription.

useQueryState and useQuerySubscription

Split reading cached data from subscribing to it when two components share one query.

  • useQueryState reads cached query status and data.
  • useQuerySubscription owns fetching and subscription behavior.
  • Keep both hooks aligned on the same endpoint argument.

selectFromResult

Narrow what a component subscribes to inside a query result it shares with others.

  • Return only fields the consuming component needs.
  • Preserve references in the selected result when data is unchanged.
  • Hoist stable empty defaults instead of creating new arrays.

Typed useAppDispatch and useAppSelector

Pre-typed wrappers so every call site keeps the store's own types.

  • Infer dispatch and state types from configureStore.
  • Reuse typed hooks throughout feature components.
  • Keep type-only imports separate to avoid runtime cycles.

Tag-driven refetching

Endpoint tags decide which hooks refetch after a mutation, instead of manual invalidation calls.

  • Declare provided tags on queries and invalidated tags on mutations.
  • Active subscriptions refetch when matching tags are invalidated.
  • Use entity IDs to avoid refreshing unrelated query results.

Toolkit foundations

configureStore

Use standard middleware and DevTools configuration with explicit root reducer and environment settings.

  • Pass the root reducer and any preloaded state explicitly.
  • Extend default middleware rather than accidentally replacing it.
  • Infer application types from the resulting configured store.

createSlice

Define case reducers and generated action creators around one state domain.

  • Define the slice name, initial state and case reducers.
  • Export generated action creators for component event handlers.
  • Mount the slice reducer under a deliberate root-state key.

Immer draft updates

Mutate a draft or return a replacement value according to Immer rules, without doing both ambiguously.

  • Modify only the draft supplied to an Immer reducer.
  • Return a new value when replacing primitive slice state.
  • Avoid implicit arrow returns from mutating array methods.

prepare callbacks

Normalize action payloads and add metadata before the reducer handles them.

  • Return a prepared payload before the action reaches reducers.
  • Attach metadata or normalize arguments in one shared location.
  • Keep reducer input shape predictable across all callers.

extraReducers

Respond to actions defined outside a slice while keeping action ownership clear.

  • Use the builder API to handle external action creators.
  • Match async thunk lifecycle actions without owning their creation.
  • Keep cross-slice reactions based on domain events.

Typed state and dispatch

Infer store types and expose reusable typed hooks for components.

  • Derive RootState from store.getState's return type.
  • Derive AppDispatch from the configured dispatch function.
  • Type reusable selectors against the actual root state.

Async Toolkit

createAsyncThunk

Generate pending, fulfilled and rejected actions around an asynchronous task.

  • Define one asynchronous payload creator for the request.
  • Handle pending, fulfilled and rejected cases in reducers.
  • Use dispatch(thunk()).unwrap() when callers need thrown failures.

Thunk cancellation

Propagate abort signals and distinguish canceled work from an ordinary application failure.

  • Pass the thunk's abort signal to supported request APIs.
  • Abort dispatched work when its owning workflow is canceled.
  • Inspect cancellation metadata before displaying an error.

rejectWithValue

Return a typed expected error payload rather than losing it in a generic thrown error.

  • Use rejectWithValue for expected validation or domain errors.
  • Declare the rejection payload type in thunk configuration.
  • Distinguish rejected payloads from unexpected serialized exceptions.

Request IDs and race handling

Accept a result only if it belongs to the still-relevant request.

  • Save the active requestId when a request begins.
  • Compare completion metadata before updating the slice.
  • Ignore late results from requests the user has superseded.

Listener middleware

React to actions or state changes with cancellable effect workflows outside reducers.

  • Register listeners for meaningful actions or state predicates.
  • Run side effects outside the reducer's pure transition.
  • Cancel obsolete listener tasks for take-latest workflows.

createEntityAdapter

Manage normalized entities with standard update helpers and derived selectors.

  • Store IDs and entity records in a normalized shape.
  • Use adapter CRUD helpers inside appropriate reducers.
  • Export generated selectors scoped to the entity slice.

RTK Query

createApi and baseQuery

Define a server-data API slice with shared request behavior and endpoint contracts.

  • Choose a base query that returns data or error consistently.
  • Register the API reducer and middleware in the store.
  • Centralize headers and request transformation at the API boundary.

Query endpoints

Cache reads by endpoint and serialized arguments and subscribe through generated hooks.

  • Define read operations as queries with explicit argument types.
  • The endpoint and serialized argument identify the cached request.
  • Share cache entries across equivalent active subscriptions.

Mutation endpoints

Represent server writes and define how successful changes affect cached queries.

  • Define write operations with their request and result types.
  • Invalidate relevant query tags after server state changes.
  • Handle mutation errors independently from cached read data.

Cache tags and invalidation

Invalidate the smallest relevant group of cached results after a mutation.

  • Provide tags that describe records or list membership.
  • Invalidate affected IDs after successful changes.
  • Use broader list tags when insertions affect collection results.

Polling and refetch policies

Balance freshness with bandwidth using focus, reconnect and polling behavior.

  • Enable focus and reconnect behavior with setupListeners.
  • Choose polling intervals that match actual freshness needs.
  • Stop unnecessary polling when the consuming view is absent.

Optimistic updates

Patch cached data immediately and roll back or invalidate when a mutation fails.

  • Apply a cache patch before the server confirms the mutation.
  • Undo the patch on failure when reversal is unambiguous.
  • Prefer invalidation when overlapping optimistic writes complicate rollback.

Streaming cache updates

Subscribe to server events for a cache entry and clean up when its lifecycle ends.

  • Open the stream from the cache-entry lifecycle handler.
  • Apply incoming changes through updateCachedData.
  • Close external subscriptions when cacheEntryRemoved resolves.

Pagination and infinite data

Model pages and arguments so cached results do not overwrite unrelated query states.

  • Include filters and page identity in query arguments.
  • Define page merging and refresh behavior deliberately.
  • Avoid mixing results from different searches into one list.

Authentication and reauthorization

Centralize credential handling and coordinate refresh behavior across failed requests.

  • Attach credentials through centralized request configuration.
  • Coordinate refresh attempts to avoid parallel token-refresh storms.
  • Retry the original request only after successful reauthorization.

Code splitting and endpoint injection

Extend an API slice without creating unnecessary isolated caches.

  • Inject feature endpoints into a shared API slice.
  • Keep a common base URL and cache tag vocabulary.
  • Export hooks from the extended API returned by injection.

Toolkit production

Serializability checks

Diagnose unsupported state or action values rather than disabling checks broadly.

  • Keep functions, promises and class instances out of normal state.
  • Investigate the exact warning path and action payload.
  • Configure narrow exceptions only for intentional integration boundaries.

Reducer injection

Load state domains dynamically with a predictable root-state contract.

  • Add reducers through a controlled dynamic-loading boundary.
  • Define the root-state type for potentially absent slices.
  • Initialize new slice state before consumers depend on it.

SSR and hydration

Create a store per request and hydrate only the state intended for the client.

  • Construct a fresh store for each server request.
  • Serialize only client-appropriate preloaded state.
  • Match the client's initial render to the server snapshot.

RTK Query testing

Test cache behavior, invalidation and errors through realistic request flows.

  • Exercise requests through a realistic mocked HTTP boundary.
  • Verify cached reuse, tag invalidation and error rendering.
  • Reset API state between independent test cases.

Performance profiling

Inspect selector changes and unnecessary subscriptions before adding memoization everywhere.

  • Measure which state changes trigger expensive component renders.
  • Inspect selected references and query subscriptions first.
  • Memoize costly derivations after identifying actual recomputation.

Redux to Toolkit migration

Adopt configureStore and slices incrementally while preserving application behavior.

  • Adopt configureStore before rewriting existing reducers.
  • Convert one reducer domain into a slice incrementally.
  • Preserve integration tests while replacing async boilerplate.

Sources

  • Redux Toolkit official documentation

Ask follow-up questions on any topic in your dashboard.

Start learning