useForm
fails with "React is null" during tests using Vitest (React 19 + Vite)
#12820
-
Issue SummaryI'm building a React library using Vite that simplifies and automates the creation of forms. Everything works as expected during development and production builds — the library builds successfully and functions correctly when consumed. However, when writing unit tests using Vitest, I encounter the following runtime error inside one of my custom hooks: Example Codeimport { z } from 'zod';
import { useForm } from 'react-hook-form';
export function useCustomForm<T>() {
const methods = useForm<z.infer<T>>({ /* ... */ });
// ^ Cannot read properties of null (reading 'useRef')
} ErrorTypeError: Cannot read properties of null (reading 'useRef')
{
"dependencies": {
"react-hook-form": "^7.55.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@vitejs/plugin-react": "4.3.4"
},
"peerDependencies": {
"react": "19.0.0",
"react-dom": "19.0.0"
}
} Notes
QuestionIs this a known compatibility issue with React 19 or Vitest? Thanks in advance for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Closed: The issue was related to React Hook Form's context. I needed to create a subcomponent directly in the test to wrap the useForm call, even though it was already used inside another component. This resolved the error. |
Beta Was this translation helpful? Give feedback.
Closed: The issue was related to React Hook Form's context. I needed to create a subcomponent directly in the test to wrap the useForm call, even though it was already used inside another component. This resolved the error.