Simple Component Example:
export default function App () {
const videoRef = useRef();
const onScreen = useOnScreen(videoRef, "-300px"); // hook for play/pause based on visibility
<div ref={videoRef} className="h-72 my-4 rounded-2xl">
<ReactPlayer
url="my-recording.mov"
loop
playing={onScreen ? true : false} />
</div>
}
I am using the useOnScreen hook from here: /
The hook works fine when running but when I change page by clicking a link using react-router-dom it throws the following error:
TypeError: Failed to execute 'unobserve' on 'IntersectionObserver': parameter 1 is not of type 'Element'.
I think the problem is in the cleanup of useEffect function (maybe the ref is already unmounted when cleanup starts to run therefore ref.current is null):
return () => {
observer.unobserve(ref.current); // here ref.current might be null
};
It works properly if I add a check before calling unobserve:
return () => {
if (ref.current) {
observer.unobserve(ref.current);
}
};
But I am not sure if this will leave the observer running and waste resources.
Please provide a solution that works and is also efficient.
Simple Component Example:
export default function App () {
const videoRef = useRef();
const onScreen = useOnScreen(videoRef, "-300px"); // hook for play/pause based on visibility
<div ref={videoRef} className="h-72 my-4 rounded-2xl">
<ReactPlayer
url="my-recording.mov"
loop
playing={onScreen ? true : false} />
</div>
}
I am using the useOnScreen hook from here: https://usehooks./useOnScreen/
The hook works fine when running but when I change page by clicking a link using react-router-dom it throws the following error:
TypeError: Failed to execute 'unobserve' on 'IntersectionObserver': parameter 1 is not of type 'Element'.
I think the problem is in the cleanup of useEffect function (maybe the ref is already unmounted when cleanup starts to run therefore ref.current is null):
return () => {
observer.unobserve(ref.current); // here ref.current might be null
};
It works properly if I add a check before calling unobserve:
return () => {
if (ref.current) {
observer.unobserve(ref.current);
}
};
But I am not sure if this will leave the observer running and waste resources.
Please provide a solution that works and is also efficient.
Share Improve this question asked Jun 27, 2021 at 15:49 RajRaj 2,0283 gold badges31 silver badges57 bronze badges 01 Answer
Reset to default 10I have faced into the same issue but solved it by using useLayoutEffect
instead of useEffect
in the useOnScreen
hook.