Skip to content

Latest commit

 

History

History
56 lines (45 loc) · 2.08 KB

persistence-and-rehydration.mdx

File metadata and controls

56 lines (45 loc) · 2.08 KB
id title sidebar_label hide_title description
persistence-and-rehydration
Persistence and Rehydration
Persistence and Rehydration
true
RTK Query > Usage > Persistence and Rehydration

 

Persistence and Rehydration

RTK Query supports rehydration via the extractRehydrationInfo option on createApi. This function is passed every dispatched action, and where it returns a value other than undefined, that value is used to rehydrate the API state for fulfilled & errored queries.

See also Server Side Rendering.

:::info

Generally, persisting API slices is not recommended and instead, mechanisms like Cache-Control Headers should be used in browsers to define cache behaviour. Persisting and rehydrating an api slice might always leave the user with very stale data if the user has not visited the page for some time. Nonetheless, in environments like Native Apps, where there is no browser cache to take care of this, persistance might still be a viable option.

:::

Redux Persist

API state rehydration can be used in conjunction with Redux Persist by leveraging the REHYDRATE action type imported from redux-persist. This can be used out of the box with the autoMergeLevel1 or autoMergeLevel2 state reconcilers when persisting the root reducer, or with the autoMergeLevel1 reconciler when persisting just the api reducer.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { REHYDRATE } from 'redux-persist'

export const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  // highlight-start
  extractRehydrationInfo(action, { reducerPath }) {
    if (action.type === REHYDRATE) {
      return action.payload[reducerPath]
    }
  },
  // highlight-end
  endpoints: (build) => ({
    // omitted
  }),
})