I made a custom hook as my intersection observer but I'm getting false and true state at the same time and twice!, first false(twice) and second true(twice) why is this happening? why state changes itself? state must be true because h3 is 100% visible.
here is the code:
App.js
import React from "react";
import "./App.css";
import useIntersectionObserver from "./hooks/useIntersectionObserver";
function App() {
const headingRef = React.useRef(null);
const { observer, state } = useIntersectionObserver({ rootMargin: "10px" });
React.useEffect(() => {
if (headingRef.current instanceof Element) {
observer.observe(headingRef.current);
}
}, []);
console.log(state);
return (
<>
<h3 ref={headingRef}>test page</h3>
<h2>test page</h2>
</>
);
}
export default App;
useIntersectionObserver custom hook:
import React from "react";
const useIntersectionObserver = (options) => {
const [state, setState] = React.useState(false);
const callback = (entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setState(true);
} else {
setState(false);
}
});
};
const observer = new IntersectionObserver(callback, options);
return { observer, state };
};
export default useIntersectionObserver;