This repository demonstrates a bug that occurs when using TanStack Start with Vitest, even in a single-package project.
When running Vitest tests in a TanStack Start application, tests fail with the error:
Cannot read properties of null (reading 'useState')
This happens because the TanStack Start Vite plugin applies optimizeDeps configuration in the Vitest environment, which interferes with how React is resolved during test execution.
This issue is fixed by PR #6074 by conditionally applying the TanStack Start plugin only when NOT in a Vitest environment.
This repo now includes an isomorphic function test in src/isomorphicEnv.test.ts backed by src/isomorphicEnv.ts using createIsomorphicFn().
In Vitest, there is currently a tradeoff:
- If
tanstackStart()runs during tests,createIsomorphicFn()resolves and the isomorphic test passes (it resolves to the client implementation in Vitest), but React hook tests fail withCannot read properties of null (reading 'useState'). - If
tanstackStart()is skipped during tests, React hook tests pass, but the isomorphic function resolves toundefinedin Vitest and the isomorphic test fails.
Before (causes error):
plugins: [
tanstackStart(),
viteReact()
]After (fixes error):
plugins: [
process.env.VITEST !== 'true' && tanstackStart(),
viteReact()
].
├── package.json
├── vite.config.ts
├── tsconfig.json
└── src/
├── App.tsx
├── App.test.tsx
├── components/
│ └── Button.tsx
├── routes/
│ └── __root.tsx
├── routeTree.gen.ts
└── router.tsx
- Node.js 18 or newer
- pnpm (this repo uses pnpm@10.28.2)
-
Install dependencies:
pnpm install
-
Run the tests (this will fail):
pnpm test -
Expected error: You should see errors like:
Cannot read properties of null (reading 'useState')
Edit vite.config.ts and change:
plugins: [
tanstackStart(),
viteReact(),
]To:
plugins: [
process.env.VITEST !== 'true' && tanstackStart(),
viteReact(),
]Then run the tests again:
pnpm testThe tests should now pass! ✅
The bug is triggered by this specific combination:
- TanStack Start plugin applied unconditionally - Runs
optimizeDepsin the test environment - Vitest test that renders a component using hooks - React resolves incorrectly (as
null) - React hook usage - Causes the "Cannot read properties of null (reading 'useState')" error
When the TanStack Start plugin runs during Vitest execution, its optimizeDeps configuration interferes with module resolution. React is resolved incorrectly (as null) when rendering components that use hooks, causing the failure.