DEV Community

Discussion on: React Sticky Event with Intersection Observer

Collapse
 
justingrant profile image
Justin Grant

Great article. I'm adapting your code for use in a project and I had two questions about stickyRefs.

First, are these refs removed from the Map when items (aka StickyBoundary + Sticky pairs) are unmounted in a dynamic list? If not, then I assume this is not good because if new items are created dynamically then you'll end up with zombie refs sticking around in that Map... and therefore a memory leak.

Second, why is this context stored at the StickyViewport level? From a cursory look at the code, it seems that this context could be stored at the StickyBoundary level instead, which would simplify things because no Map would be needed, and would remove the memory leak risk noted above because if a section is unmounted then the context provider would be unmounted too. Is this correct?

And one more question: I'm assuming that only one <Sticky> can be inside a <StickyBoundary>. Is this correct? If yes then while moving the context as noted above, I may add some error handling to prevent duplicate <Sticky> elements in a boundary.

Collapse
 
dance2die profile image
Sung M. Kim

Thank you for the questions and thoughtful comments/suggestions, Justin.

First, are these refs removed from the Map when items (aka StickyBoundary + Sticky pairs) are unmounted in a dynamic list?

No, they are not. Sticky refs are added using addStickyRef but not removed on unmount. That's a very nice catch. So <Sticky /> component should probably call a method like (not implemented in the post) removeStickyRef to destroy the ref.

Second, why is this context stored at the StickyViewport level?

You can have multiple StickyViewport components, each of which can fire different intersection events. The StickyViewport has containerRef, against which intersection observer (for each Sticky component) events are fire, not relative to StickyBoundary.

I'm assuming that only one can be inside a . Is this correct?

You can have multiple Sticky components but event will fire for the last one
Yes. You can have one Sticky component under StickyBoundary. I believe the original implementation in Google doc didn't allow this either (maybe too restrictive)...