Skip to content

Latest commit

 

History

History
60 lines (45 loc) · 2.3 KB

code-splitting.mdx

File metadata and controls

60 lines (45 loc) · 2.3 KB
id title sidebar_label hide_title description
code-splitting
Code Splitting
Code Splitting
true
RTK Query > Usage > Code Splitting: dynamic injection of endpoints

 

Code Splitting

RTK Query makes it possible to trim down your initial bundle size by allowing you to inject additional endpoints after you've set up your initial service definition. This can be very beneficial for larger applications that may have many endpoints.

injectEndpoints accepts a collection of endpoints, as well as an optional overrideExisting parameter.

Calling injectEndpoints will inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. (Unfortunately, it cannot modify the types for the original definition.)

A typical approach would be to have one empty central API slice definition:

// Or from '@reduxjs/toolkit/query' if not using the auto-generated hooks
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

// initialize an empty api service that we'll inject endpoints into later as needed
export const emptySplitApi = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  endpoints: () => ({}),
})

and then inject the api endpoints in other files and export them from there - that way you will be sure to always import the endpoints in a way that they are definitely injected.

// file: emptySplitApi.ts noEmit
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const emptySplitApi = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  endpoints: () => ({}),
})

// file: extendedApi.ts
import { emptySplitApi } from './emptySplitApi'

const extendedApi = emptySplitApi.injectEndpoints({
  endpoints: (build) => ({
    example: build.query({
      query: () => 'test',
    }),
  }),
  overrideExisting: false,
})

export const { useExampleQuery } = extendedApi

:::tip In development mode, if you inject an endpoint that already exists and don't explicitly specify overrideExisting: true, the endpoint will not be overridden and you will get a warning about it. You will not see the warning in production and the existing endpoint will just be overriden, so make sure to account for this in your tests. :::