Skip to content

Allow extending a core RTK Query API with React hooks functionality #5134

@markerikson

Description

@markerikson

There's a few related open issues that that are variations on this, so writing this up officially.

Problem Statement

RTK Query's createApi currently exists in two forms: there's the UI-agnostic form in @reduxjs/toolkit/query that only generates thunks for each endpoint, and the React-enhanced version in @reduxjs/toolkit/query/react that also builds in all of the hook generation capabilities.

However, these are incompatible with each other. More specifically, if you call the core createApi() and also call the React createApi() these create similar API slice objects, but there's no way to take an existing core API slice object and extend it with the additional React capabilities.

This is a problem in a couple ways. The biggest is that you may want to use RTKQ on the server (such as in a Server Component / SSR environment), so it would be reasonable to import your RTKQ API slice object and dispatch the thunks on the server... but those environments don't like hook imports and throw on import. So, you have to create a core/non-React API slice, which is duplicated effort and imports.

In general, it's a reasonable architectural idea to say "I have a core RTKQ API slice created, I would like to extend or copy it to add the hooks functionality too".

Architecture

At the technical level, the React hooks generation is done via calling buildCreateApi() with the additional "React Hooks Module". This has an init() method that calls buildHooks() internally, then exposes a {injectEndpoint() } object. buildCreateApi() then does const initializedModules = modules.map(m => m.init(ctx)), and then later for (const m of modules) { m.injectEndpoint() }.

Conceptually, it feels like we ought to be able to make this into a separated step process somehow. I don't know what that would look like architecturally, or type-wise.

Ben tried to play with this briefly in #4128 , but I haven't looked at it.

This is almost definitely a "3.0"-level project because it would require significant changes to the public API.

Also potentially has impacts around SSR and RSC use cases somehow.

Semi-related issues:

Early experiment PR:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions