I am trying to use the intersection observer API to conditionally display items in a CSS grid when the user starts scrolling, but it seems to go into an infinite rendering loop. Here is my code.
Here is the link to my live code on StackBlitz
Also what I'm trying to achieve is not render too many items on the screen when I can avoid it. I'm not sure if display: none
actually makes the browser work less. If this is not the correct way, please let me know.
Thanks for reading my question. Any help is highly appreciated.
Problem: Same Ref on 1000 Elements
You have 1000
GridItem
components which are all getting the same callback refsetRefs
. They all receive the same value ofinView
even though we know that at any given time some are in view and others are not. What ends up happening is that each items overwrites the previously set ref such that all 1000 items receive a booleaninView
that represents whether the last item in the list is in view -- not whether it is itself in view.Solution:
useInView
for Each ElementIn order to know whether each individual component is in view or not, we need to use the
useInView
hook separately for each element in the list. We can move the code for each item into its own component. We need to pass this component its numberix
and the options for theuseInView
hook (we could also just pass down the root ref and create theoptions
object here).StackBlitz Link