如何用 createApi 自动生成 React Hooks?

解读

国内一线/二线前端面试中,Redux Toolkit(RTK)已成“标配”。当面试官抛出“createApi 怎么自动生成 React Hooks”时,他真正想考察的是:

  1. 你是否把 RTK Query 当成“数据层”而非“简单请求封装”;
  2. 你是否理解 自动生成 背后的编译期机制;
  3. 你是否能在真实业务里权衡 Hooks 命名、缓存 Key、乐观更新、错误重试等细节。
    一句话:不仅要“会用”,更要“知道它怎么长出来”,以及“出了问题从哪下手”。

知识点

  1. createApi 是 RTK Query 的核心工厂函数,接收 reducerPath、baseQuery、tagTypes、endpoints 等字段。
  2. endpoints 里每个 query/mutation 配置项,在编译期会被 @reduxjs/toolkit 内部的 buildHooks 逻辑映射成:
    • useXxxQuery
    • useXxxLazyQuery
    • useXxxSuspenseQuery(RTK 2.0+)
    • useXxxMutation
      命名规则:取 endpoints 的 key,首字母大写,再拼接固定后缀。
  3. 自动生成 依赖 TypeScript 的模板字面量类型推导,因此必须开启 @reduxjs/toolkit/query/react 入口,否则只生成 Thunk ActionCreator,不会生成 Hooks。
  4. 生成的 Hooks 内部已自动:
    • 订阅 Store 的 api.reducerPath 切片;
    • 根据 queryCacheKey 做请求去重;
    • 在组件卸载后按 cacheTimeout 清理数据;
    • 触发 refetchOnFocus/refetchOnReconnect。
  5. 国内项目常要求“统一错误码处理”与“Token 刷新”,需在 baseQuery 里封装 axios 实例或 fetch 拦截器,并配合 retry 条件函数实现“刷新重试队列”。
  6. 若需“分页、下拉加载更多”,可直接用 useXxxQuery(arg, { skip, pollingInterval, selectFromResult }),其中 selectFromResult 可记忆化派生数据,避免组件级 reselect。
  7. 代码分割场景:用 injectEndpoints 动态注入,保证首屏不加载全部 Hooks,契合国内“微前端/子应用”诉求。

答案

  1. 安装依赖
    npm i @reduxjs/toolkit react-redux
    
  2. 创建 api 切片(/src/services/userApi.ts)
    import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
    
    export const userApi = createApi({
      reducerPath: 'userApi',                 // 必须唯一
      baseQuery: fetchBaseQuery({
        baseUrl: '/api',
        prepareHeaders: (headers, { getState }) => {
          const token = (getState() as RootState).auth.token;
          if (token) headers.set('Authorization', `Bearer ${token}`);
          return headers;
        }
      }),
      tagTypes: ['User'],                     // 供 invalidatesTags 使用
      endpoints: (builder) => ({
        getUserById: builder.query<User, string>({
          query: (id) => `user/${id}`,
          providesTags: (result, error, id) => [{ type: 'User', id }]
        }),
        updateUser: builder.mutation<User, Partial<User> & { id: string }>({
          query: ({ id, ...patch }) => ({
            url: `user/${id}`,
            method: 'PUT',
            body: patch
          }),
          invalidatesTags: (res, err, { id }) => [{ type: 'User', id }]
        })
      })
    });
    
    // 自动生成的 Hooks,命名固定
    export const { useGetUserByIdQuery, useLazyGetUserByIdQuery, useUpdateUserMutation } = userApi;
    
  3. 注入 Store(/src/store/index.ts)
    import { configureStore } from '@reduxjs/toolkit';
    import { userApi } from '@/services/userApi';
    
    export const store = configureStore({
      reducer: {
        [userApi.reducerPath]: userApi.reducer
      },
      middleware: (getDefault) => getDefault().concat(userApi.middleware)
    });
    
    export type RootState = ReturnType<typeof store.getState>;
    
  4. 组件层使用(React 18 + TypeScript)
    import { useGetUserByIdQuery } from '@/services/userApi';
    
    const UserCard: React.FC<{ id: string }> = ({ id }) => {
      const { data, isLoading, isError, refetch } = useGetUserByIdQuery(id, {
        pollingInterval: 30000,          // 国内常用“心跳”策略
        skip: !id                        // 防御性编程
      });
    
      if (isLoading) return <Skeleton />;
      if (isError) return <Button onClick={refetch}>重试</Button>;
    
      return <div>{data.nickname}</div>;
    };
    
  5. 验证自动生成
    在 VSCode 里跳转到 useGetUserByIdQuery 定义,可看到类型文件里已生成:
    export declare const useGetUserByIdQuery: TypedUseQueryHook<string, User, typeof userApi.reducerPath>;
    
    证明 createApi 在编译期完成了 Hooks 的静态注入,无需手写任何 useEffect/useSelector。

拓展思考

  1. 如何自定义 Hook 命名?
    国内团队往往有“业务域”概念,例如把 getUserById 改成 useUserInfoQuery。目前 RTK Query 不支持直接 alias,但可在外层再包一层自定义 Hook,并重新导出,保持团队命名规范。
  2. SSR(Next.js)场景下如何保证数据脱水?
    在 getServerSideProps 里手动调用 store.dispatch(userApi.endpoints.getUserById.initiate(id)),随后使用 api.util.getRunningOperationPromises() 进行 Promise.all 收集,完成后再把 State 序列化到 HTML,即可实现“同构直出”。
  3. 多环境 baseUrl 治理
    国内项目常区分“开发/测试/预发/正式”四套域名,可在 fetchBaseQuery 外层再做一层“动态 baseUrl 工厂”,根据 import.meta.env.VITE_API_PREFIX 或 window.RUNTIME_CONFIG 实时切换,避免重新打包。
  4. 与 React-Query 的选型差异**
    如果团队已深度使用 Redux(如共享复杂业务切片),RTK Query 的 “数据即状态” 理念能减少一套外部缓存,降低心智负担;反之,若项目只有轻量请求场景,React-Query 的独立缓存可能更灵活。面试时可结合团队现状给出“可迁移”方案,体现技术广度。