Remove EventListener after adding
In React, it is important to remove eventListener after this component is unmounted.
1) Otherwise it might still been called on an unmounted object, then result in memory leak or error
2) Each time, the dependency changes, it might adds eventListener multiple times
Correct example:
useEffect(() => {
if (haveMoreData) {
window.addEventListener("scroll", tryLoadMore);
}
return () => {
window.removeEventListener("scroll", tryLoadMore);
};
}, [searchParams, haveMoreData]);
Load more Content Implementation
However, we only want to load data when it reaches the bottom.
To implement this, we can use useRef() to bind to a div element.
Then, we can use Element.getBoundingClientRect() to get the relative position it has relative to the screen.
Comments
Post a Comment