Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Loaded virtual module is unable to access parent react context #17492

Closed
7 tasks done
Neo-Ciber94 opened this issue Jun 16, 2024 · 2 comments · Fixed by Neo-Ciber94/vite-ssr-react-context-issue#1
Closed
7 tasks done

Comments

@Neo-Ciber94
Copy link

Describe the bug

I'm not fully sure if this is a bug or is how it works.

I have a react tree with a context on top:

function ServerEntry({ App }: { App: ComponentType }) {
  const theme = "dark";

  return (
    <ThemeContext.Provider value={theme}>
      <Root>
        <App />
      </Root>
      <script
        id="theme"
        dangerouslySetInnerHTML={{
          __html: `window.initialTheme = ${JSON.stringify(theme)}`,
        }}
      />
    </ThemeContext.Provider>
  );
}

The App is an export from a virtual module:

export async function handleRequest(
  _req: http.IncomingMessage,
  res: http.ServerResponse
) {
  const viteServer = getViteServer();
  const { default: Component } = await viteServer.ssrLoadModule("virtual:app");
  const { pipe } = renderToPipeableStream(<ServerEntry App={Component} />, { ... })
}

But when I try to access the context, I get an error because is reset to null:

import { createContext, useContext } from "react";

export type Theme = "dark" | "light";
export const ThemeContext = createContext<Theme | null>(null);
export function useTheme() {
  const theme = useContext(ThemeContext);
  if (!theme) {
    throw new Error('"ThemeContext" was not available');
  }
  return theme;
}

Reproduction

https://github.com/Neo-Ciber94/vite-ssr-react-context-issue

Steps to reproduce

yarn install and yarn dev

System Info

System:
    OS: Windows 11 10.0.22631
    CPU: (8) x64 Intel(R) Core(TM) i5-8300H CPU @ 2.30GHz
    Memory: 3.74 GB / 15.88 GB
  Binaries:
    Node: 20.14.0 - D:\Program Files\nodejs\node.EXE
    Yarn: 1.22.22 - D:\Program Files\nodejs\yarn.CMD
    npm: 10.7.0 - D:\Program Files\nodejs\npm.CMD
    pnpm: 9.3.0 - D:\Program Files\nodejs\pnpm.CMD
    bun: 1.1.10 - ~\.bun\bin\bun.EXE
  Browsers:
    Edge: Chromium (126.0.2592.56)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    @vitejs/plugin-react: ^4.3.1 => 4.3.1
    vite: ^5.3.1 => 5.3.1

Used Package Manager

yarn

Logs

Error: "ThemeContext" was not available
at Module.useTheme (.../src/context.tsx:10:11)
at App (virtual:app:8:39)

Validations

@hi-ogawa
Copy link
Collaborator

hi-ogawa commented Jun 17, 2024

This is an expected behavior. It's important to note that you have src/context.tsx imported from two worlds, namely inside and outside of vite ssr module graph:

  • (outside) vite.config.ts -> entry.server.tsx -> context.tsx
  • (inside) ssrLoadModule("virtual:app") -> context.tsx

You might need to rework architecture so that entry.server.tsx only lives in vite ssr module graph via ssrLoadModule("/src/entry.server").

@Neo-Ciber94
Copy link
Author

That explains the behaviour, it felt like the component imported was separated from my app.

Thank you very much @hi-ogawa for the explanation and providing a fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants