Skip to content

Instantly share code, notes, and snippets.

@3nvi
Created May 1, 2021 16:16
Show Gist options
  • Save 3nvi/164090964fb43ee7073fb45fef922a7d to your computer and use it in GitHub Desktop.
Save 3nvi/164090964fb43ee7073fb45fef922a7d to your computer and use it in GitHub Desktop.
A way to defer rendering of a big list
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);
};
@jacubsmith
Copy link

Great piece of work dude!

@3nvi
Copy link
Author

3nvi commented May 17, 2021

Ah cheers!

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