Created
May 1, 2021 16:16
-
-
Save 3nvi/164090964fb43ee7073fb45fef922a7d to your computer and use it in GitHub Desktop.
A way to defer rendering of a big list
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
const Defer = ({ chunkSize, children }) => { | |
const [renderedItemsCount, setRenderedItemsCount] = React.useState(chunkSize); | |
const childrenArray = React.useMemo(() => React.Children.toArray(children), [ | |
children | |
]); | |
React.useEffect(() => { | |
if (renderedItemsCount < childrenArray.length) { | |
window.requestIdleCallback( | |
() => { | |
setRenderedItemsCount( | |
Math.min(renderedItemsCount + chunkSize, childrenArray.length) | |
); | |
}, | |
{ timeout: 200 } | |
); | |
} | |
}, [renderedItemsCount, childrenArray.length, chunkSize]); | |
return childrenArray.slice(0, renderedItemsCount); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great piece of work dude!