Skip to content

[Bug]: React Context Race Condition in Vite Module Federation with Manifest #287

@larevalos

Description

@larevalos

Describe the bug

Bug Report: React Context Race Condition in Vite Module Federation with Manifest

Environment

  • React: 18.3.1
  • Vite:
  • @vitejs/plugin-react: 4.3.4
  • @module-federation/vite: 1.2.6
  • TypeScript: 5.6.3
  • OS: Windows
  • Mode: Issue occurs only in production/build mode

Description

When using Module Federation with Vite in a React application, an intermittent race condition occurs when consuming remote modules through the mf-manifest.json approach. This race condition causes React contexts to fail, resulting in hook errors because React isn't fully initialized before federated components try to use context providers.

The issue only occurs in production/build mode. Development mode (both host and remote) works correctly.

Error Details

Multiple React-related errors occur, all indicating that React context is not properly initialized:

  1. React Context Null Error:
Uncaught TypeError: Cannot read properties of null (reading 'useContext')
    at react_production_min.useContext (react.production.min.js:24:495)
    at ApolloProvider (ApolloProvider.js:8:25)
  1. Hook Errors such as:
useEffect, useRef etc is undefined
  1. Error with my context providers not being able to share instance between host and remote:

Root Cause

The race condition appears to be in how the mf-manifest.json approach loads shared dependencies. The manifest approach creates timing issues where host React contexts aren't fully initialized before remote components try to access them.

These timing issues appear to be exacerbated by the asynchronous nature of manifest-based loading compared to direct remoteEntry.js loading.

Workaround

I used the remoteEntry instead of manifest. What I lost there is that I was generating the remoteEntry in the remote app with a hash in the name on every new build. If I want to reference the remote entry with hash in the host I will have to find a workaround for that so that I won't need to update anything in the host application on every new build.

Steps to Reproduce

I couldn't reproduce the issue in smaller apps, they work!! It only happens in a bigger app where there are a lot of shared dependencies.

Version

6.2.5

Reproduction

I couldn't create a minimal reproduction

Relevant log output

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions