Recheck rv()
against previous value
in useEffect
callback in useReactiveVar
#8135
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.
While rereading the code @jcreighton added in #7652, I remembered it's safe to access a reactive variable
rv
by callingrv()
in auseEffect
callback (without going throughuseReactiveVar
).Taking advantage of this insight, we should be able to compare the latest variable value to the previous
value
before deciding whether to callrv.onNextChange(setValue)
in the effect callback function, if/when that callback fires. If the values already disagree, we can skip listening and just callsetValue
right away.In React
<StrictMode>
, there will be two initialrv()
values generated prior to theuseIsomorphicEffect
callback (which may never fire), but those values should always be the same, unless the reactive variable somehow gets updated in between the double renders. I don't think that's possible, since React invokes those renders synchronously, one after the other.The key difference between this approach and calling
rv.onNextChange
synchronously inrender
is that (in this new approach) we can safely ignore the extravalue
without doing anything to clean up its resources, whereas callingrv.onNextChange
inrender
made us additionally responsible for calling the extracancel
function returned by the extrarv.onNextChange
call, which was not easy/possible.If I'm on the right track here, then we finally have a way to "listen" for reactive variable changes that happen before the effect callback fires, even if that callback is noticeably delayed.