Skip to content

fix: Conditionally rendering fields in <StrictMode> #576

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

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions packages/react-form/src/useField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down