Skip to content

Micro front ends — state (Redux Toolkit) ​

How to structure a microfrontend's (MFE's) own state with Redux Toolkit (RTK). my-growth-mfa is the first MFE to complete this migration and is the reference implementation — kudos-mfa, stable-apps-mfa still use Jotai / jotai-tanstack-query and should follow this pattern when they migrate; admin-mfa has the RTK store and is migrating its pages one slice at a time. This page assumes you already know RTK; it focuses on the Luna-specific integration decisions, not RTK fundamentals.

See Micro front ends — overview for the Module Federation contract this pattern has to respect.

Why Redux Toolkit, and why now ​

The MFE rules mandate RTK for MFE state and forbid introducing @tanstack/query-core / jotai-tanstack-query in new work. my-growth-mfa fully replaced its Jotai + jotai-tanstack-query store with RTK and RTK Query, with zero Jotai left in its source — use its src/store/ as the template.

Key decisions ​

The MFE owns its own store — it does not join the host's ​

The MFE creates and provides its own Provider store={store}; it does not attach to the host's Redux store. Two reasons:

  • Version incompatibility. The host is on react-redux v7 / RTK v1.8 with hand-rolled reducers; a new MFE migration is v9 / v2. A v7 and a v9 react-redux context are not interoperable — you can't join the host's Provider from a different react-redux major.
  • Not shared anyway. Module Federation's shared config on both the host and every MFE only lists react and react-dom — Redux/RTK aren't singletons across the federation boundary, so there's no mechanism to join the host's store even if the versions matched. Don't add them to shared to work around this; it's not worth the version-pinning burden across host and every MFE.

Cross-app state still comes from the host — don't duplicate it ​

State that's genuinely the host's (ANDi directory, business units) stays exactly as it was: consumed via the host's exposed host/store useStore() hook. Only migrate the MFE's own local state (UI state, and server state fetched through host-exposed API clients) into RTK. In my-growth-mfa, src/store/andi/ and src/store/businessUnits/ are untouched host-store proxies — they were never Jotai and aren't part of this migration.

Server state → RTK Query, not @tanstack/react-query ​

Replace jotai-tanstack-query with RTK Query (createApi) rather than adding @tanstack/react-query — that keeps one state library and one cache in the MFE, and is what the MFE rules require for new work.

A custom baseQuery for host-exposed APIs ​

The host doesn't expose raw HTTP endpoints — it exposes pre-built axios API objects (host/configApi, host/performanceReviewApi, etc.), each with its own methods (fetchConfig(domain, key), fetchReviewById(id), ...). RTK Query's fetchBaseQuery assumes a URL-based fetch, so it doesn't fit. Instead, write a small custom baseQuery that runs whatever async function an endpoint's query returns, and normalises the result into RTK Query's { data } / { error } shape:

ts
// src/store/hostApiBaseQuery.ts
export const hostApiBaseQuery =
  (): BaseQueryFn<() => Promise<unknown>, unknown, HostApiError> =>
  async (run) => {
    try {
      return { data: await run() };
    } catch (err) {
      return { error: /* normalised error */ };
    }
  };

Each endpoint's query is then a thunk that calls the host API object directly:

ts
// src/store/config/configApi.ts
export const configApi = createApi({
  reducerPath: 'configApi',
  baseQuery: hostApiBaseQuery(),
  endpoints: (builder) => ({
    getConfig: builder.query<DnaReviewPeriodConfig | undefined, GetConfigArgs>({
      query: ({ domain, key }) => async () => {
        const res = await hostConfigApi.fetchConfig(domain, key);
        return res[0];
      },
    }),
  }),
});

This keeps the host API contract completely unchanged — components still get typed RTK Query hooks (useGetConfigQuery) with caching, skip, and tag invalidation for free.

skip replaces jotai-tanstack-query's enabled:

ts
useGetReviewsByAndiIdQuery(andiId, { skip: !andiId });

Tag-based invalidation (tagTypes, providesTags, invalidatesTags) replaces the manual refetch() calls jotai-tanstack-query needed after a mutation — a createReview mutation that invalidates the AndiReviews/TeamReviews tags automatically refetches any query providing them, with no explicit refetch() wiring in the component.

Provider placement — a real gotcha ​

An MFE's federation-exposed entry components (e.g. PerformanceReviews, TeamPerformanceReviews) are mounted directly by the host via React.lazy(() => import('myGrowthApp/PerformanceReviews')) — they never pass through the MFE's own App.tsx. So the store <Provider> has to be added at each exposed component, not only in App.tsx for standalone dev.

The subtler trap: a component cannot call useAppDispatch/useAppSelector/an RTK Query hook and also render the <Provider> that's supposed to supply that context — the hook call happens in the component's own render, which is outside the <Provider> it returns. Split the exposed component into an outer wrapper (renders the Provider) and an inner *Content component (uses the hooks):

tsx
const PerformanceReviewsContent = (props: PerformanceReviewsProps) => {
  const dispatch = useAppDispatch(); // fine — inside the Provider
  // ...
  return <StoreProvider>{/* ... */}</StoreProvider>;
};

const PerformanceReviews = (props: PerformanceReviewsProps) => (
  <Provider store={store}>
    <PerformanceReviewsContent {...props} />
  </Provider>
);

export default PerformanceReviews;

Get this wrong and you'll see could not find react-redux context value; please ensure the component is wrapped in a <Provider> — both at runtime and in component tests.

RTK Query freezes cached data — don't mutate it

RTK Query deep-freezes cached data with Immer in development. Any code that mutates a query result in place — most commonly Array.prototype.sort(), which sorts in place and returns the same array — will throw Cannot assign to read only property '0' of object '[object Array]'. jotai-tanstack-query didn't freeze its cache, so this kind of bug can be latent in code carried over from a Jotai MFE. Fix by copying before mutating: [...items].sort(...) instead of items.sort(...).

Target folder structure ​

my-growth-mfa's src/store/:

PathPurpose
store/index.tscombineReducers + configureStore, a makeStore() factory (fresh store per test), RootState/AppDispatch types
store/hooks.tsTyped useAppDispatch / useAppSelector
store/hostApiBaseQuery.tsThe custom base query described above
store/config/configApi.ts, store/templates/performanceReviewApi.tsOne createApi per host API surface
store/toast/toastSlice.ts, store/reviewsUi/reviewsUiSlice.tscreateSlice for local UI state
store/testUtils.tsxrenderWithStore(ui, { preloadedState }) test helper, built on makeStore()
store/andi/, store/businessUnits/Unchanged host-store proxies — not part of the RTK migration

Testing ​

Use renderWithStore instead of hand-wrapping a Provider per test:

ts
import { renderWithStore as render } from '@store/testUtils';

render(<MyComponent />, { preloadedState: { reviewsUi: { andiId: 'andi-1' } } });

Mock RTK Query hooks and slice hooks directly rather than mocking the whole state module — mocking the whole module drops the reducer export the real store still imports:

ts
vi.mock('@store/templates', async () => {
  const actual = await vi.importActual<typeof import('@store/templates')>('@store/templates');
  return { ...actual, useGetReviewsByAndiIdQuery: vi.fn() };
});

importActual keeps the reducer and other real exports intact; only the hook you're stubbing is replaced.

Reusability — what's shared vs. local ​

store/index.ts's makeStore/typed-hooks factory, hostApiBaseQuery, renderWithStore, and the folder layout above are the generic, copy-paste starting point for the next MFE migration. They currently live in my-growth-mfa and admin-mfa — extract them into a shared @bhag-business-platform/luna-redux package once a second MFE actually needs them, not before. Copy the pattern for kudos-mfa / stable-apps-mfa first; premature extraction for a single consumer just adds package-versioning overhead.

Summary ​

  • The MFE owns its own RTK store and Provider; it does not join the host's store, and host cross-app state keeps coming from host/store.
  • Server state is RTK Query via a custom hostApiBaseQuery that wraps the host's axios API objects — not @tanstack/react-query.
  • Add the Provider at every federation-exposed entry component, and never call store hooks in the same component that renders that Provider.
  • RTK Query freezes cached data — don't mutate query results in place.
  • The pattern lives in my-growth-mfa/src/store/; copy it for the next MFE migration before considering a shared package.

Made with ❤️ by the Luna team