Skip to main content

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.

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

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