Skip to content

Instantly share code, notes, and snippets.

@pflevy
Last active August 9, 2020 14:17
Show Gist options
  • Save pflevy/67957a25877133e45edd4c7e33d796cf to your computer and use it in GitHub Desktop.
Save pflevy/67957a25877133e45edd4c7e33d796cf to your computer and use it in GitHub Desktop.
Creating custom react hooks. Infinite scrolling hook example.
import { useState } from "react";
export const useInfiniteScroll = (start = 30, pace = 10) => {
const [limit, setLimit] = useState(start);
window.onscroll = () => {
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
setLimit(limit + pace);
}
};
return limit;
};
// Instructions
// 1 - Call hook on a variable inside the component
// let inifiniteScroll = useInfiniteScroll()
// 2 - Use .splice() on disered array before mapping
// array.splice(0, infiniteScroll).map()
@ThisIsMissEm
Copy link

You should also be using useCallback here to remove the event listener when unrendering the element

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment