♻️ A tiny React hook for rendering large datasets like a breeze.
♻️ A tiny React hook for rendering large datasets like a breeze.
A tiny React hook for rendering large datasets like a breeze.
isScrolling indicator to you for UI placeholders or performance optimization.react.When rendering a large set of data (e.g. list, table, etc.) in React, we all face performance/memory troubles. There're some great libraries already available but most of them are component-based solutions that provide well-defineded way of using but increase a lot of bundle size. However, a library comes out as a hook-based solution that is flexible and headless but using and styling it can be verbose (because it's a low-level hook). Furthermore, it lacks many of the useful features.
React Cool Virtual is a tiny React hook that gives you a better DX and modern way for virtualizing a large amount of data without struggle .
To use React Cool Virtual, you must use [email protected] or greater which includes hooks.
This package is distributed via npm.
$ yarn add react-cool-virtual
# or
$ npm install --save react-cool-virtual⚠️ This package using ResizeObserver API under the hook. Most modern browsers support it natively, you can also add polyfill for full browser support.
If you're not using a module bundler or package manager. We also provide a UMD build which is available over the unpkg.com CDN. Simply use a `
Once you've added this you will have access to the `window.ReactCoolVirtual.useVirtual` variable.
### Basic Usage
Here's the basic concept of how it rocks:
```js
import useVirtual from "react-cool-virtual";
const List = () => {
const { outerRef, innerRef, items } = useVirtual({
itemCount: 10000, // Provide the total number for the list items
itemSize: 50, // The size of each item (default = 50)
});
return (
))}
);
};✨ Pretty easy right? React Cool Virtual is more powerful than you think. Let's explore more use cases through the examples!
This example demonstrates how to create a fixed size row. For column or grid, please refer to CodeSandbox.
import useVirtual from "react-cool-virtual";
const List = () => {
const { outerRef, innerRef, items } = useVirtual({
itemCount: 1000,
});
return (
))}
);
};This example demonstrates how to create a variable size row. For column or grid, please refer to CodeSandbox.
import useVirtual from "react-cool-virtual";
const List = () => {
const { outerRef, innerRef, items } = useVirtual({
itemCount: 1000,
itemSize: (idx) => (idx % 2 ? 100 : 50),
});
return (
))}
);
};This example demonstrates how to create a dynamic (unknown) size row. For column or grid, please refer to CodeSandbox.
import useVirtual from "react-cool-virtual";
const List = () => {
const { outerRef, innerRef, items } = useVirtual({
itemCount: 1000,
itemSize: 75, // The unmeasured item sizes will refer to this value (default = 50)
});
return (
))}
);
};The scrollbar is jumping (or unexpected position)? It's because the total size of the items is gradually corrected along with an item that has been measured. You can tweak the
itemSizeto reduce the phenomenon.
This example demonstrates how to create a real-time resize row (e.g. accordion, collapse, etc.). For column or grid, please refer to CodeSandbox.
import { useState, forwardRef } from "react";
import useVirtual from "react-cool-virtual";
const AccordionItem = forwardRef(({ children, height, ...rest }, ref) => {
const [h, setH] = useState(height);
return (
);
});
const List = () => {
const { outerRef, innerRef, items } = useVirtual({
itemCount: 50,
});
return (
);
};This example demonstrates how to create a list with RWD to provide a better UX for the user.
import useVirtual from "react-cool-virtual";
const List = () => {
const { outerRef, innerRef, items } = useVirtual({
itemCount: 1000,
// Use the outer's width (2nd parameter) to adjust the item's size
itemSize: (_, width) => (width > 400 ? 50 : 100),
// The event will be triggered on outer's size changes
onResize: (size) => console.log("Outer's size: ", size),
});
return (
))}
);
};If the item size is specified through the function of
itemSize, please ensure there's no the measureRef on the item element. Otherwise, the hook will use the measured (cached) size for the item. When working with RWD, we can only use either of the two.
This example demonstrates how to make sticky headers with React Cool Virtual.
import useVirtual from "react-cool-virtual";
const List = () => {
const { outerRef, innerRef, items } = useVirtual({
itemCount: 1000,
itemSize: 75,
stickyIndices: [0, 10, 20, 30, 40, 50], // The values must be provided in ascending order
});
return (
);
})}
);
};
…
js
const { scrollTo, scrollToItem } = useVirtual();
const scrollToOffset = () => {
// Scrolls to 500px
scrollTo(500, () => {
// Do whatever you want through the callback
});
};
const scrollToItem = () => {
// Scrolls to the 500th item
scrollToItem(500, () => {
// Do whatever you want through the callback
});
// We can control the alignment of the item with the `align` option
// Acceptable values are: "auto" (default) | "start" | "center" | "end"
// Using "auto" will scroll the item into the view at the start or end, depending on which is closer
scrollToItem({ index: 10, align: "auto" });
};React Cool Virtual provides the smooth scrolling feature out of the box, all you need to do is turn the smooth option on.
const { scrollTo, scrollToItem } = useVirtual();
// Smoothly scroll to 500px
const scrollToOffset = () => scrollTo({ offset: 500, smooth: true });
// Smoothly scroll to the 500th item
const scrollToItem = () => scrollToItem({ index: 10, smooth: true });
…
> For more cool easing effects, please [check it out](https://easings.net).
### Infinite Scroll
It's possible to make a complicated infinite scroll logic simple by just using a hook, no kidding! Let's see how possible .
#### Working with [Skeleton Screens](https://uxdesign.cc/what-you-should-know-about-skeleton-screens-a820c45a571a)
…
#### Working with A Loading Indicator
…
### Pre-pending Items
This example demonstrates how to pre-pend items and maintain scroll position for the user.
…
### Filtering Items
When working with filtering items, we can reset the scroll position when the `itemCount` is changed by enabling the [resetScroll](#resetscroll) option.
```js
import { useState } from "react";
import useVirtual from "react-cool-virtual";
const List = () => {
const [itemCount, setItemCount] = useState(100);
const { outerRef, innerRef, items } = useVirtual({
itemCount,
// Resets the scroll position when the `itemCount` is changed (default = false)
resetScroll: true,
});
return (
))}
);
};This example demonstrates the scenario of sticking/unsticking the scroll position to the bottom for a chatroom.
…This example demonstrates how to handle input elements (or form fields) in a virtualized list.
…When dealing with forms, we can use React Cool Form to handle the form state and boost performance for use.
import useVirtual from "react-cool-virtual";
import { useForm } from "react-cool-form";
const defaultValues = new Array(20).fill(false);
const Form = () => {
const { outerRef, innerRef, items } = useVirtual({
itemCount: defaultValues.length,
});
const { form } = useForm({
defaultValues: { todo: defaultValues },
removeOnUnmounted: false, // To keep the value of unmounted fields
onSubmit: (formData) => alert(JSON.stringify(formData, undefined, 2)),
});
return (
))}
);
};React requires keys for array items. I'd recommend using an unique id as the key as possible as we can, especially when working with reordering, filtering, etc. Refe
No open issues yet, or sync has not completed.