Skip to content

Commit

Permalink
Remove unnecessary effect in useField()
Browse files Browse the repository at this point in the history
  • Loading branch information
sebelga committed Jul 15, 2020
1 parent fe70433 commit 1910571
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -517,28 +517,13 @@ export const useField = <T>(
serializeOutput,
]);

form.__addField(field as FieldHook<any>); // Executed first (1)

useEffect(() => {
/**
* NOTE: effect cleanup actually happens *after* the new component has been mounted,
* but before the next effect callback is run.
* Ref: https://kentcdodds.com/blog/understanding-reacts-key-prop
*
* This means that, the "form.__addField(field)" outside the effect will be called *before*
* the cleanup `form.__removeField(path);` creating a race condition.
*
* TODO: See how we could refactor "use_field" & "use_form" to avoid having the
* `form.__addField(field)` call outside the effect.
*/
__addField(field as FieldHook<any>); // Executed third (3)
}, [field, __addField]);
form.__addField(field as FieldHook<any>);

useEffect(() => {
return () => {
// Remove field from the form when it is unmounted or if its path changes.
isUnmounted.current = true;
__removeField(path); // Executed second (2)
__removeField(path);
};
}, [path, __removeField]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,11 @@ export function useForm<T extends FormData = FormData>(
(path, value) => {
const _formData$ = getFormData$();
const currentFormData = _formData$.value;
const nextValue = { ...currentFormData, [path]: value };
_formData$.next(nextValue);

if (currentFormData[path] !== value) {
_formData$.next({ ...currentFormData, [path]: value });
}

return _formData$.value;
},
[getFormData$]
Expand Down

0 comments on commit 1910571

Please sign in to comment.