Open fabb opened 4 years ago
No, the useMemo
is problematic because it would always update on every render, because options
is an object, and clients very probably won't make it stable using useMemo
or useCallback
. This makes it worse, since it would cause re-observing for every render, and also break triggerOnce
.
Ah, in this hook, the elements of the options
array are just directly used in the deps array:
https://github.com/thebuilder/react-intersection-observer/blob/master/src/useInView.tsx#L51
But note that they still have a bug when using an array for threshold
, so I'd recommend to use JSON.stringify()
in that case: https://github.com/thebuilder/react-intersection-observer/issues/248#issuecomment-599999725
While researching another problem, I noticed that
useIntersectionObserver
is never updating thecallback
:Since the initial state of
useState
is only executed for the first run of the hook, that meansintersectObs
will always point to an instance ofIntersectionObserver
with thehandleIntersect
function of the first run of the hook.But
handleIntersect
changes for every run of the hook, and even whenuseCallback
would be used for it, that still would change depending on its dependency array.I do not really understand why this seems to make no problems? Theoretically, when either
callback
ortriggerOnce
is changing between runs ofuseIntersectionObserver
, it would not pick up these changes, and still execute the firstintersectObs
callback. Maybe I need to test this differently.If this is really a problem, a solution would be to use something like this:
But this also doesn‘t update the
options
of the IntersectionObserver. Or maybe useuseMemo
for the IntersectionObserver?The two ideas could also be combined to both avoid unnecessary resubscribes when only the callback changes, and allow to change the options.