'ReactJS Intersection Observer only working once if I change something in App.tsx... if I refresh the browser, it will not work work anymore
I am facing an issue where the intersection observer only working once I have changed something in App.tsx and saved it via "ctrl+s" App.tsx:
import React, {
lazy,
RefObject,
Suspense,
useState,
useEffect,
ReactElement,
useRef,
FunctionComponent,
} from "react"
import "./App.css"
import Navbar from "./components/Navbar/Navbar"
import Hero from "./components/Hero/Hero"
import { useElementOnScreen } from "./hooks/useElementOnScreen"
import { LegacyRef } from "react"
// const SkillList = lazy(() => import("./components/SkillList/SkillList"))
import SkillList from "./components/SkillList/SkillList"
const App: FunctionComponent = (): ReactElement => {
const options = {
threshold: 0,
}
const refComp = useRef<Element>(null)
const isVisible = useElementOnScreen(refComp, options)
return (
<div>
<Navbar />
<Hero />
<div>neuer component</div>
<Suspense fallback={<div>Loading...</div>}>
<div ref={refComp as LegacyRef<HTMLDivElement>}>
{isVisible && <SkillList />}
</div>
</Suspense>
</div>
)
}
export default App
Then everything seems to work. Here is a screenshot: react intersection observer triggered
Once I refresh the browser, it will not be triggered anymore. I have to change App.tsx again, then it will trigger again. Why is this?
Here is the hook I am using in App.tsx
``
import React, { createRef } from "react"
import {
useRef,
useState,
useEffect,
RefObject,
useMemo,
LegacyRef,
} from "react"
interface OptionsI {
threshold: number
}
export const useElementOnScreen = (
ref: RefObject<Element>,
options: OptionsI
) => {
const [isVisible, setIsVisible] = useState(false)
console.log(isVisible)
// const optionsMemo = useMemo(() => {
// return options
// }, [options])
const containerRef = ref.current
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
const [entry] = entries
console.log(entry)
setIsVisible(entry.isIntersecting)
console.log("ISSS")
}, options)
if (containerRef) observer.observe(containerRef)
return () => {
if (containerRef) observer.unobserve(containerRef)
}
})
return isVisible
}
What I am trying to achieve is to lazy load a component, once its container div is in view.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|