react-hook-form FormProvider not working when using it from internal component library

Viewed 1191

I use react-hook-form FormProvider in my FormContext component, like this: (this component is in my component library)

const FormContext: FunctionComponent<Props> = ({
  children,
  ...options
}) => {
  const formMethods = useForm(options);

  return (
    <FormProvider {...formMethods}>
      {children}
    </FormProvider>
  );
};

export default FormContext;

This is my component: (in Content component I use useFormContext hook)

<FormContext>
   <Content />
</FormContext>

When I run my app I got this error:

Uncaught TypeError: Cannot destructure property 'reset' of '(0 , react_hook_form__WEBPACK_IMPORTED_MODULE_2__.useFormContext)(...)' as it is null.

package.json in my internal component library:

{
  "devDependencies": {
    "react-hook-form": "6.9.6",
  },
  "peerDependencies": {
    "react-hook-form": ">=7.0.0",
  }
}
1 Answers

I think I just fixed this issue in my case. What I ended up doing was matching some of the package's tsconfig.json settings to the app's settings. Specifically, I changed the following to match between the two:

...
"compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": ["dom", "dom.iterable", "esnext"],
    "jsx": "react-jsx",
...

I haven't poked at this to see which specific value fixed things, but I have a feeling it might have been the "lib" values. Maybe this will help?

[Edit] Also worth noting that I reverted back to v7.21.0, but I'm not sure that was the issue. I'll update it to current shortly and see if it's still working. [Edit 2] Looks like it's still working with v7.22.5.


8/30/2022 UPDATE: we are currently using react-hook-form 7.34.2. We also switched to using Parcel to build the package in the prepack script (which automatically runs before the publish script command). Parcel seems to work better than tsc.

We also set the peerDependencies to the exact version being used, and make sure the project(s) using the package has the same version of react-hook-form installed. If the versions differ, there's a good change it'll break, based on our experience.

Here is our current full tsconfig.json file, if it helps:

{
  "include": ["src"],
  "exclude": ["node_modules", "dist"],
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": ["dom", "dom.iterable", "esnext"],
    "jsx": "react-jsx",
    "outDir": "dist",

    "noEmit": false,
    "skipLibCheck": true,
    "strict": true,
    "declaration": true,
    "pretty": true,
    "strictNullChecks": true,
    "noUnusedParameters": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "suppressImplicitAnyIndexErrors": true
  }
}
Related