There are times when we need to process and filter data in frontend. Writing the search and filter logic can be an overhead and repeating task. With the help of useFilter hook you don't need to write the filter/search logic.
Also, while dealing with large amount of data, it often takes up lot memory and keeps the main thread block till the filtering process is completed. This results into bad user experience. In order to keep the main thread free and run the web application without any glitches we can leverage the use of Web Worker which runs on a separate thread and can share the messages with main thread.
I, along with my friend Yash Joshi developed a react hook
that lets you filter and search data using webworker.useFilter
Installation
yarn add @promise_learning/usefilter
npm install @promise_learning/usefilter
Usage
We recommend usingfor rendering large data set. Also usereact-window
hook with search so that with every hit a search query is not triggered.useDebounce
import { useFilter } from '@promise_learning/usefilter';
import from './data.json';
// handle this using the state in your app
const searchData = {
query: '',
fields: ['name'],
};
const filtersData = {
category: ['Sci Fiction'],
};
export const App = () => {
const { loading, data: result } = useFilter({ data, search: searchData, filters: filterData });
if (loading) {
return <div>loading..</div>
}
return (
<>
// render result
</>
)
}
data
: Required | Array of objectssearch
: Optional | Object with following keys: query
-> query string and fields
-> object keys to search onfilters
: Optional | Object with key as a field from object in an array and value could be possible value arrays / stringloading
: boolean stating if web worker is processing the data or notdata
: filtered dataEnjoy using
@promise_learning/usefilter
and shower some love to github repo
🎉Also published at https://dev.to/lakhansamani/react-usefilter-hook-26c4