1. Invalid Hook Call Error:
React hooks rely on the singleton instance of React to manage their internal state. If there are multiple versions of React loaded (e.g., one from your project and another from a dependency like msal-react), the hook calls won’t behave as expected.

2. Why It Works in the Component but Not the Hook:
When calling useMsal directly in App.tsx, it might be using the same React instance as your app. However, when used in your custom hook, there could be an indirect dependency path causing a mismatched React instance.

3. Ensure a Single React Instance:

  • Open package.json in your project and check for React version mismatches.
  • Run npm ls react or yarn list react to ensure there’s only one version of React in the dependency tree.
  • If multiple versions exist, use the resolutions field in package.json (if using Yarn) or npm dedupe to resolve them.

4. Alias React in Webpack:
If the issue persists, ensure all modules use the same React instance:

  • Add the following to your Webpack configuration
resolve: {
  alias: {
    react: path.resolve('./node_modules/react'),
  },
},

5. Reinstall Node Modules:

  • Delete node_modules and reinstall dependencies:
rm -rf node_modules package-lock.json
npm install

Support On Demand!

ReactJS

Related Q&A