Search code examples
reactjsreduxredux-toolkitrtk-query

Redux Toolkit Queries or/and memoized selectors?


in my rtkq project, i call as an example, useGetNotesQuery in other pages and components, since i provide tags, rtkq will check the cache before making another api call, to which if the cache has changed, it will load from the cache without an api call, and if it hasnt changed, then load the cache. Is there then any point to also use memoized selectors then if rtkq already watches and has its own cache system?


Solution

  • I think what you are asking about is effectively for an apples and oranges comparison. Redux-toolkit Query (RTKQ) is a tool that serves a completely different use case than what selector functions are used for.

    Redux-Toolkit Query State selector functions
    • Is a query state management tool.
    • Is an abstraction built over Redux-Toolkit, it manages API requests, caches responses, invalidates cached responses, manages the initialized/loading/fetching states.
    • Uses selector functions. "React Hooks users will most likely never need to use these directly, as the hooks automatically use these selectors as needed."
    In other words, the useGetNotesQuery hook already uses a memoized selector internally. The RTKQ hooks abstract the micromanagement of the initiating and caching of data from your APIs.
    Selector functions are simply functions that select a specific slice, or chunk, of state in a Redux store. Some selector functions memoize their result value based on their inputs.

    Is there then any point to also use memoized selectors then if rtkq already watches and has its own cache system?

    I'm generally inclined to say "no", use memoized selectors where it makes sense, i.e. when you are selecting computed or derived state from the redux store composed from your state slices. It doesn't make much sense to try to use selectors to select the query state that the app's api slices manage, use the query hooks.