fix: Conditionally rendering fields in <StrictMode> #576
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Addresses #571.
TL;DR
It seems like the bug can be tracked to
useField
creating duplicate instances of the field (FieldApi
) in strict mode and not cleaning them up properly. This PR at this point is just a proof of concept for a solution.Details of the bug
Basically, the
useField
hook runs twice in strict mode, and creates a new instance ofFieldApi
every time it runs (source):I think that problem is that the cleanup function only runs once, because it's wrapped in a
useIsomorphicEffectOnce
hook source:Honestly, there's a lot of things happening here, so I'm not a 100% percent sure I read the situation correctly. 😆
My solution and questions
I thought the best way to approach this issue is preventing a duplicate
FieldInstance
from being created, by checking if there's an instance already in the initialization function of theuseState
hook inuseField
. My question is: how dangerous is it? 🤣 In what cases would the field have multiple instances (in general, not just at this point)? Also, I'd love to understand a bit more abouttanstack/store
, especially if it's important here (a quick overview would be enough). I'm happy to get guidance on Discord, if a (or rather the) maintainer has time for it.