score:0
Your component will render before the element is being observed by the Intersection Observer so it's expected that the state would be false on the first render (or first couple renders). This isn't really a problem but there are a couple improvements you could make to get more consistent behavior.
The first is to store the observer object in a ref so that only one is created:
function useIntersectionObserver(options) {
const [state, setState] = React.useState(false);
// store the observer in a ref so only one is created
const observer = React.useRef(new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
console.log("is visible")
setState(true);
} else {
console.log("not visible")
setState(false);
}
});
}, options))
return { observer: observer.current, state };
}
And the second is to add the observer to your useEffect's dependency array and to return a cleanup function. This will ensure that your useEffect to register the observer is only run when observer changes and that it's properly cleaned up.
function App() {
const headingRef = React.useRef(null);
const { observer, state } = useIntersectionObserver({ rootMargin: "10px" });
React.useEffect(() => {
if (observer && headingRef.current) {
observer.observe(headingRef.current);
}
// return cleanup function
return () => {
if (observer) {
observer.disconnect();
}
}
// correctly specify the observer as a dependency to this side effect
}, [observer]);
return (
<>
<h3 ref={headingRef}>test page</h3>
<h2>test page</h2>
</>
);
}
Full codepen here: https://codepen.io/spencercwood/pen/mdqegBZ?editors=0011
On the codepen open up the console and you'll see that the IntersectionObserver only prints out "is visible" once. Try resizing the rendered content window so that it's no longer visible and you'll see "not visible" printed, etc.
Source: stackoverflow.com
Related Query
- Mocking react custom hook return value as a module with Jest returns wrong value
- custom hook returns wrong value
- custom react hook returns default value in initial render
- List element value returns wrong values when accessing attribute
- React custom Hook using useRef returns null for the first time the calling component Loads?
- Testing return value of a custom hook
- How to let react consider returned value of custom hook as stable identity?
- React useState hook returns old state value despite it being updated
- setState with value of previously returned custom hook
- Function called from a react custom hook returns 'is not a function'
- Why custom hook returns results twice
- React: how to avoid re-rendering a component with a hook that returns always the same value but changes its inner state
- ClickEvent fires twice and returns the wrong value for .contains()
- Custom hook returns Promise but resolves inside useEffect
- How to update state value of variable that uses custom Hook
- React - what is wrong with my custom hook for click outside of element?
- React, return boolean value from custom hook
- React returning a function in a custom hook, whose internal hook returns an object
- updating a useState to the value that it's already holding inside of a custom React hook causes infinite re-render
- Why does a custom hook that uses another hooks value via useContext only shows its initial value?
- In the custom hook test, the state is not changed from the initial value
- How to update custom hook value
- useLocation Hook returns wrong path
- How to mock react custom hook return value as a module with Jest
- React hook form how to pass value from custom component to controller with already assign own on change?
- Using React Context in a custom hook always returns undefined
- React Hook useState returns undefined for props value but props value appears on textbox value
- Custom react hook not updating it's value
- setup function returns undefined when testing a custom hook usePrevious
- Custom hook to subscribe to array of observables and take the latest value from each
More Query from same tag
- React+Redux. Connect doesn't update state of component
- Map and filter confusion
- Megre results of one API call with another React.js Javascript
- Use fs module in React.js,node.js, webpack, babel,express
- React Context not working with server side rendering
- Reading environment variable in run time after running npm build for a create-react-app based project
- My ternary operarion with data from an arrray of objects in React is not working
- ReactJS how to set input Textfield to display current Date and time?
- React extract param from url
- Next.js catch all route not working as expected with getStaticPaths
- Reset Button for highchart drilldown pie
- Best practice: prepare props only once for rendering
- Get form data in ReactJS
- Chaining two react APIs together where the output of one goes into the input of the second. Uses Axios/Async
- How to customize theme in Semantic-UI-React (not Semantic-UI)?
- How to makes height auto for React Bootstrap forms
- Trying to work with the mapping function and it keeps gives me this error?
- Can I run multiple React programs from bash and view them on the web?
- Clear Apollo cache between tests
- Reactjs setEmail is not a function onChange although it is function
- How do I populate a JSON array with the data from my MYSQL database?
- saving state into localstorage in react
- Generic composable component props for interface
- How to display the contents inside a div using flexbox
- Loop an array get undefined
- How to clear react-select value after formik form submission?
- How to test a component with a nested container with React and Redux?
- How to authorize a user when he logs-in in react js?
- Accessing 3rd party React component in web forms application
- JavaScript Object is not assigned properly