Skip to content

Instantly share code, notes, and snippets.

@MichaelDimmitt
Last active May 8, 2024 17:49
Show Gist options
  • Save MichaelDimmitt/124153fc217edf88058e970a197a26cf to your computer and use it in GitHub Desktop.
Save MichaelDimmitt/124153fc217edf88058e970a197a26cf to your computer and use it in GitHub Desktop.
React Form Hook, how watch works notes.

React hook form notes, How the watch function works:

Summary:
The watch operator uses .subscribe function that creates a generator. That generator progresses forward by next() being called. This then gets evaluated to see if a re-render needs to occur and gets passed to useState.

useWatch():
useWatch.ts#L68
useWatch.ts#L184

Note: uses a syntax similar to a generator, when .next is called it executes a callback function that triggers updateValue from the useState.

useForm():
useForm.ts#L99

watch():
createFormControl.ts#L94
createFormControl.ts#L922

The useSubscribe creates a generator that powers the .next function.
useSubscribe.ts

.subscribe feels like a js generator since it uses .next. However, it does not use the * syntax. I will investigate further at another time to see exactly what .subscribe is doing.

Update:

useSubscribe uses a subject onto which they push what they call obeservables. createSubject.ts#L18

useSubscribe's subject which comes from control.subjects.state exists on a control. formControl gets called here: link

A control is created from createFormControl.ts#L94 and subjects is called here createFormControl.ts#L149 which is a default export of createSubject - which gets renamed from Subject as part of the default export.

Observer logic below:
(I think in this context, an observable is what is visible each re-render.)

What is an example of an observer that gets passed in here? useSubscribe says: _props.current.subject.subscribe({next: _props.current.next}); and one level higher up:

props.current.next is a function that checks if it should update and then does update the state for the watch.

aha!, the next function gets called here on re-render createSubject.ts#L22

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment