From 8cd8e7a8c68a0c9a58996fa844d120b87154b42e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=BCl=C3=B6p=20Kov=C3=A1cs?= <kovacs.fulop@gmail.com> Date: Mon, 22 Jan 2024 22:50:58 +0100 Subject: [PATCH] I think this commit fixes a bug in conditionally rendering a field in strict mode, but it might create others --- packages/react-form/src/useField.tsx | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/react-form/src/useField.tsx b/packages/react-form/src/useField.tsx index 2bb39c2ec..ca6a31aaa 100644 --- a/packages/react-form/src/useField.tsx +++ b/packages/react-form/src/useField.tsx @@ -76,6 +76,28 @@ export function useField< .filter((d) => d !== undefined) .join('.') + // NOTE: I know, it's a type error, but this is not the final code + const previousInstance: + | FieldApi< + TParentData, + TName, + TFieldValidator, + TFormValidator, + DeepValue<TParentData, TName> + > + | undefined = Object.values(formApi.getFieldInfo(name).instances)[0] + + if (previousInstance) { + /* NOTE: In <StrictMode>, an instance of `FieldApi` is already created + the first time this hook ran, but it will not get cleaned up on its own, + when the component unmounts, because of the useIsomorphicEffectOnce() hook, + which doesn't execute the cleanup function on "dummy React cycles". + + This code change seems to solve https://github.com/TanStack/form/issues/571 + */ + return previousInstance + } + const api = new FieldApi({ ...opts, form: formApi as never,