Skip to content

Commit

Permalink
Perf: avoid expensive removeAll on unmount (#39)
Browse files Browse the repository at this point in the history
* Perf: on unmount, call removeAll with no argument

Calling `removeAll` with no argument is vastly more performant when one
needs to remove all documents. Therefore, upon unmount, we now use the
performant no-arg version.

See #38

* Fix

* Clarify docs

* Add regression test for errors on unmount
  • Loading branch information
lucaong committed Jul 6, 2023
1 parent 862b43c commit c4f7037
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ yarn add react-minisearch

There are three main ways to use `react-minisearch`: the `useMiniSearch` hook, the `withMiniSearch` higher-order component, or the `WithMiniSearch` wrapper component.

All three way take the following arguments (or props for the wrapper component):

- The initial collection of documents to add to the index. Note: this is just
the initial collection, and mutating this argument won't cause reindexing.
To add or remove documents after initialization, use the functions
`add`/`addAll`/`remove`/`removeAll`/`discard`, etc.
- The `MiniSearch` configuration options

#### Using the useMiniSearch hook:

```jsx
Expand Down
4 changes: 4 additions & 0 deletions src/react-minisearch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,10 @@ const testComponent = (Component: React.FC<Props>) => {

const items = wrap.update().find('.results li')
expect(items).not.toExist()

expect(() => {
wrap.unmount()
}).not.toThrow()
})

it('removes a document by id', () => {
Expand Down
8 changes: 2 additions & 6 deletions src/react-minisearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export interface UseMiniSearch<T = any> {
miniSearch: MiniSearch<T>
}

export function useMiniSearch<T = any> (documents: T[], options: Options<T>): UseMiniSearch<T> {
export function useMiniSearch<T = any> (documents: readonly T[], options: Options<T>): UseMiniSearch<T> {
const optionsRef = useRef(options)
const miniSearchRef = useRef<MiniSearch<T>>(new MiniSearch<T>(options))
const documentByIdRef = useRef<{ [key: string]: T }>({})
Expand Down Expand Up @@ -147,11 +147,7 @@ export function useMiniSearch<T = any> (documents: T[], options: Options<T>): Us

useEffect(() => {
utils.addAll(documents)

return () => {
utils.removeAll(documents)
}
}, [utils, documents])
}, []) // eslint-disable-line react-hooks/exhaustive-deps

return {
searchResults,
Expand Down

0 comments on commit c4f7037

Please sign in to comment.