I am lazy-loading components on a React page by using react-intersection-observer:
import React from "react";
import { useInView } from "react-intersection-observer";
const LazyComponent = ({ LoadableComponent, ...rest }) => {
const { ref, inView } = useInView({ rootMargin: "50px 0px" });
return <div ref={ref}>{inView && <LoadableComponent {...rest} />}</div>;
};
const MyComponent = (props) => {
return (
<div style={{ height: "4000px", backgroundColor: "blue" }}>
<p>This is the top of MyComponent.</p>
</div>
);
};
export default function App() {
return (
<div className="App">
<h1>Title</h1>
<div style={{ height: "1000px", backgroundColor: "green" }}></div>
<LazyComponent LoadableComponent={MyComponent} />
<div style={{ height: "1000px", backgroundColor: "red" }}></div>
</div>
);
}
You can run the code in this sandbox.
What happens correctly: When I scroll down from the green zone and the lazy-loaded component (in blue) comes in view, it starts loading its code.
The problem is: when I scroll all the way down to the section at the bottom (in red), the lazy-loaded component will unmount. When I scroll back up and the lazy-loaded component comes in view again, it mounts again and the page 'jumps' to the top of this component.
How can I prevent this, so that scrolling is smooth and no jumping occurs?