perf: memoize fuse search results with useMemo (#71)

Memoise the value of fuse based off of the search list to prevent reinstantiating it on search keypress.
This commit is contained in:
Chris Kerr
2023-05-15 14:37:17 +10:00
committed by GitHub
parent f6ac8104b2
commit 99b27240ec
+7 -3
View File
@@ -1,5 +1,5 @@
import Fuse from "fuse.js"; import Fuse from "fuse.js";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState, useMemo } from "react";
import Card from "@components/Card"; import Card from "@components/Card";
import slugify from "@utils/slugify"; import slugify from "@utils/slugify";
import type { BlogFrontmatter } from "@content/_schemas"; import type { BlogFrontmatter } from "@content/_schemas";
@@ -30,12 +30,16 @@ export default function SearchBar({ searchList }: Props) {
setInputVal(e.currentTarget.value); setInputVal(e.currentTarget.value);
}; };
const fuse = new Fuse(searchList, { const fuse = useMemo(
() =>
new Fuse(searchList, {
keys: ["title", "description"], keys: ["title", "description"],
includeMatches: true, includeMatches: true,
minMatchCharLength: 2, minMatchCharLength: 2,
threshold: 0.5, threshold: 0.5,
}); }),
[searchList]
);
useEffect(() => { useEffect(() => {
// if URL has search query, // if URL has search query,