Redux Toolkit

repository·master·Indexed 11 days ago

https://github.com/reduxjs/redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development. It simplifies Redux by providing sensible defaults, reducing boilerplate, and including powerful features like RTK Query for data fetching. The toolkit includes @reduxjs/rtk-codemods to automate the migration of legacy API usage patterns to modern builder callback syntax for createReducer and createSlice.

Tokens
188.4K
Snippets
454
Records
601
Agent score
94%

What's inside Redux Toolkit

  1. What is Redux Toolkit (RTK)?

    master

    Redux Toolkit (RTK) is the official, recommended approach for writing Redux logic. It wraps the core redux package and provides essential API methods and common dependencies to simplify standard Redux tasks, prevent common mistakes (like accidental state mutation), and reduce boilerplate code.

    Key benefits include:

    • Simplified Store Setup: Uses configureStore to handle middleware and DevTools automatically.
    • Easier Reducer Logic: Uses createSlice to allow writing "mutating" logic that is safely converted to immutable updates via Immer.
    • Automatic Boilerplate Reduction: Automatically generates action creators and action type strings.
    • Built-in Best Practices: Includes essential tools like redux-thunk and DevTools integration by default.
  2. Explore RTK Query Infinite Queries usage patterns

    master

    This example demonstrates how to implement various infinite loading and pagination strategies using RTK Query's infinite query endpoint support. It covers the following patterns:

    • Basic pagination: Standard page-by-page loading.
    • Infinite scrolling: Loading more data as the user reaches the end of a list.
    • Bidirectional cursors: Loading data in both directions (e.g., previous and next).
    • Offset + limit: Using traditional offset and limit parameters for data fetching.
    • Max pages: Restricting the total number of pages that can be loaded.
    • React Native FlatList: Integrating infinite query patterns with the FlatList component in React Native.
  3. Understand the Redux Toolkit + Next.js App Router CI Example

    master

    This example is a CI fixture used to verify @reduxjs/toolkit published artifacts. It demonstrates how to integrate Redux Toolkit into a modern Next.js environment using the App Router, React 19, and Turbopack.

    Key architectural patterns demonstrated include:

    • Server-Side Store Creation: Using React Server Components to import the core RTK Query entry point (@reduxjs/toolkit/query) and build a store on the server. This exercises RTK within the React Server Components graph.
    • Client-Side Store Provisioning: Using a StoreProvider component that creates a store per client instance with a lazy useState initializer, following the recommended pattern for Next.js integration.
    • Module Resolution: Demonstrates how the client half of the app resolves RTK through Next's bundler using module-sync / module conditions to land on dist/redux-toolkit.modern.mjs.
  4. Convert GitHub issues to Markdown

    master

    The GitHub Issue to Markdown Converter is a standalone TypeScript script that transforms GitHub issue JSON files (including comments) into a readable Markdown format. It is useful for creating dev plans or documentation from issue discussions.

    Features

    • Converts JSON to clean Markdown.
    • Includes metadata like author, date, and comment count.
    • Formats comments with author, date, and author association badges (e.g., MEMBER, CONTRIBUTOR).
    • Uses only built-in Node.js modules (no external dependencies).
    • Supports running via Bun, ts-node, or compiled Node.js.
  5. What is RTK Query and why use it?

    master

    RTK Query is a powerful data fetching and caching tool included as an optional addon in the Redux Toolkit package. It is designed to simplify loading data in web applications by eliminating the need to hand-write manual data fetching and caching logic.

    Key problems it solves:

    • Loading State: Automatically tracks loading states to show UI spinners.
    • Duplicate Requests: Avoids making multiple requests for the same data.
    • Optimistic Updates: Supports making the UI feel faster by predicting server responses.
    • Cache Management: Manages cache lifetimes as users interact with the UI.

    Unlike standard Redux state management, RTK Query is purpose-built for the 'data fetching' concern, providing features like auto-generated React hooks, cache entry lifecycle management (e.g., for WebSockets), and TypeScript support.

  6. What is RTK Query and how to use it

    master

    RTK Query is an optional addon within @reduxjs/toolkit designed for data fetching and caching. It simplifies loading data in web applications by providing an API interface layer.

    Entry Points

    You can import RTK Query using two different entry points depending on your needs:

    1. Standard entry point: For general use.
    2. React-specific entry point: Automatically generates React hooks corresponding to your defined endpoints.

    Core APIs

    • createApi(): The central function used to define endpoints and data retrieval logic. A common rule of thumb is to use "one API slice per base URL."
    • fetchBaseQuery(): A lightweight wrapper around the browser fetch API, recommended as the baseQuery for most users.
    • <ApiProvider />: A provider to use if you do not already have a Redux store.
    • setupListeners(): A utility to enable refetchOnMount and refetchOnReconnect behaviors.
    /* React-specific entry point that automatically generates
       hooks corresponding to the defined endpoints */
    import { createApi } from '@reduxjs/toolkit/query/react'
    
    /* Standard entry point */
    import { createApi } from '@reduxjs/toolkit/query'
  7. What is RTK Query?

    master

    RTK Query is an advanced data fetching and caching tool built on top of Redux Toolkit. It is designed to simplify common data loading patterns in web applications by providing automated caching, request de-duplication, and loading state management. It is included in the @reduxjs/toolkit package as an addon.

    Key benefits include:

    • Centralized API Definition: Unlike libraries that use many custom hooks in different files, RTK Query encourages defining your entire API (endpoints, base URLs, and cache logic) in one central location.
    • Automatic De-duplication: If multiple components subscribe to the same query, RTK Query ensures only one network request is made and synchronizes the loading state across all components.
    • Built-in State Tracking: Automatically provides status booleans like isLoading, isFetching, isSuccess, and isError.
  8. Overview of Redux Toolkit APIs

    master

    Redux Toolkit provides a suite of tools to simplify Redux development by reducing boilerplate and automating common setup tasks. Key APIs include:

    • configureStore(): A wrapper around createStore that simplifies configuration, automatically combines reducers, adds middleware (including redux-thunk), and enables Redux DevTools.
    • createSlice(): The primary way to build logic; it combines createReducer() and createAction() to automatically generate a slice reducer, action creators, and action types.
    • createReducer(): Uses the immer library to allow writing 'mutative' code for immutable state updates.
    • createAction(): Generates action creator functions.
    • combineSlices(): Combines multiple slices into one reducer, supporting lazy loading.
    • createListenerMiddleware(): A lightweight alternative to Sagas or Observables for responding to actions or state changes.
    • createAsyncThunk(): Generates thunks that automatically dispatch pending, resolved, and rejected actions based on a Promise.
    • createEntityAdapter(): Provides reusable reducers and selectors for managing normalized data.
    • createSelector(): Re-exported from reselect for efficient memoized selectors.
  9. Overview of the generated API slice from createApi

    master

    When you call createApi, it returns an API service "slice" object that contains all the Redux logic needed to interact with your defined endpoints. This object includes:

    • Redux Integration: A reducer to manage cached data and a middleware to manage cache lifetimes and subscriptions.
    • Endpoints: Logic (thunks and selectors) for each endpoint you defined.
    • Code Splitting: Methods like injectEndpoints to add more endpoints later.
    • Utilities: A utils object for manual cache management (e.g., invalidating tags, prefetching).
    • React Hooks: If using the React-specific entry point, auto-generated hooks for components.

    Best Practice: One API Slice per Base URL

    Typically, you should only have one API slice per base URL. For example, if your API uses /api/posts and /api/users, create one slice with /api/ as the base URL and define both posts and users as endpoints.

    Why?

    1. Automatic Tag Invalidation: Only works within a single API slice. If you use multiple slices, you cannot invalidate a tag in Slice A from an endpoint in Slice B.
    2. Performance: Every createApi call generates its own middleware. Adding many separate middlewares to the store increases the performance cost as every dispatched action must be checked against every middleware.
    const api = createApi({
      baseQuery: fetchBaseQuery({ baseUrl: '/' }),
      endpoints: (build) => ({
        // ...
      }),
    })
  10. What is createListenerMiddleware?

    master

    A createListenerMiddleware is a lightweight Redux middleware designed for handling side effects in response to dispatched actions or state changes. It serves as a simpler alternative to Redux Sagas or Observables, functioning conceptually like React's useEffect hook but triggered by Redux store updates.

    Key features include:

    • Access to dispatch and getState (similar to thunks).
    • Support for complex async workflows using functions like take, condition, pause, fork, and unsubscribe via the listenerApi.
    • Ability to define listeners statically during setup or dynamically at runtime.
    • Ability to run logic based on action types, action creators, matchers, or custom predicates (which can check state changes).
  11. Use tags for automated cache invalidation

    master

    RTK Query uses a tag system to manage cache invalidation.

    • providesTags: Used in queries to declare which tags (or specific tagged entities) the cached data contains.
    • invalidatesTags: Used in mutations to declare which tags should be invalidated when the mutation succeeds.

    When a mutation invalidates a tag, RTK Query automatically refetches any active queries that provide that tag.

    type Post = { id: string; title: string }
    
    export const api = createApi({
      reducerPath: 'api',
      baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
      tagTypes: ['Post'],
      endpoints: (build) => ({
        getPosts: build.query<Post[], void>({
          query: () => 'posts',
          providesTags: (result) =>
            result
              ? [...result.map(({ id }) => ({ type: 'Post' as const, id })), 'Post']
              : ['Post'],
        }),
        updatePost: build.mutation<Post, Pick<Post, 'id' | 'title'>>({
          query: ({ id, title }) => ({
            url: `posts/${id}`,
            method: 'PATCH',
            body: { title },
          }),
          // Invalidates the specific post by ID and the general 'Post' list tag
          invalidatesTags: (_result, _error, { id }) => [{ type: 'Post', id }],
        }),
      }),
    })