Last active
August 9, 2020 14:17
-
-
Save pflevy/67957a25877133e45edd4c7e33d796cf to your computer and use it in GitHub Desktop.
Creating custom react hooks. Infinite scrolling hook example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should also be using useCallback here to remove the event listener when unrendering the element