Blog>
Snippets

Server Caching with Redux in Next.js

Outline an approach for server-side cache management within a Redux store for a Next.js app, configured for optimal performance and state reuse.
import { createSlice, configureStore } from '@reduxjs/toolkit';
import { useMemo } from 'react';

// Redux slice
const cacheSlice = createSlice({
  name: 'cache',
  initialState: {},
  reducers: {
    setCache: (state, action) => {
      const { key, value } = action.payload;
      state[key] = value;
    },
    clearCache: state => {
      return {};
    }
  }
});

// Middlewares for the store
const cacheMiddleware = store => next => action => {
  const result = next(action);
  const state = store.getState();
  // Custom logic to persist state to server cache could be added here
  return result;
};

// Redux store
export const initializeStore = (preloadedState) => {
  return configureStore({
    reducer: {
      cache: cacheSlice.reducer,
    },
    middleware: getDefaultMiddleware => getDefaultMiddleware().concat(cacheMiddleware),
    preloadedState,
  });
};

// Hook for client side to initialize and use the store with caching
export function useStore(initialState) {
  const store = useMemo(() => initializeStore(initialState), [initialState]);
  return store;
}
This code defines a Redux store with a slice for caching and a middleware for persisting state changes to the server cache. The useStore hook uses 'useMemo' to memoize the store creation based on the initial state passed to ensure that the same store is used during hydration.