I have a page where there are around 10-15 cards fetching data from APIs and printing graphs. When I load the page they all start fetching data and render a graph which is making page little lagging as obvious.
As a part performance optimization I am trying to implement react-intersection-observer package so only card visible on screen will call APIs and show graph. But that seems to be not working, there is no error so not able to find what's wrong.
If I just comment
<GridLayout
className="layout"
layout={layout}
cols={12}
rowHeight={100}
width={800}
>
and
</GridLayout>
Then everything works fine, But not with it
I tried 2-3 different approaches but so far no luck, any help would be appreciated.
It seems that the reason might be
Card
fromantd
does not forwardref
, whileref
is needed for eitherreact-intersection-observer
orreact-grid-layout
to function.While there is no official guide to keep these libraries work together, perhaps the
<InView/>
component provided byreact-intersection-observer
could be a possible approach, since it acceptsforwardRef
, and can serve as a wrapper component forCard
, while it functions as the observer as well.Potential drawbacks of this approach include
<InView />
would be an extra wrapper forCard
, which might or might not be a problem depending on the use case.Forked demo with the experimental approach: codesandbox
Card
with the implementation is separated as a custom component to keep the parent cleaner. TheonChange
property on<InView />
can accept a callback to run what is needed when the component is in view.A state
isInView
is defined here just for testing, and I think a custom state would probably be a more suitable approach here than using the render props, which is limited inside<InView />
and also depends onref
to function.The props forwarded to the custom component are required by
react-grid-layout
according to their document.Parent component now only include any logic to define
layout
:On a side note, because
<InView />
is already wired up with the required functionalities, the wrappedCard
fromantd
could be replaced by a custom component with necessary styles, if preferred.