From 99b27240ec4058de89af0f69b25c146d51771b10 Mon Sep 17 00:00:00 2001 From: Chris Kerr Date: Mon, 15 May 2023 14:37:17 +1000 Subject: [PATCH] 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. --- src/components/Search.tsx | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/components/Search.tsx b/src/components/Search.tsx index 39c96ef..3e72f31 100644 --- a/src/components/Search.tsx +++ b/src/components/Search.tsx @@ -1,5 +1,5 @@ import Fuse from "fuse.js"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useRef, useState, useMemo } from "react"; import Card from "@components/Card"; import slugify from "@utils/slugify"; import type { BlogFrontmatter } from "@content/_schemas"; @@ -30,12 +30,16 @@ export default function SearchBar({ searchList }: Props) { setInputVal(e.currentTarget.value); }; - const fuse = new Fuse(searchList, { - keys: ["title", "description"], - includeMatches: true, - minMatchCharLength: 2, - threshold: 0.5, - }); + const fuse = useMemo( + () => + new Fuse(searchList, { + keys: ["title", "description"], + includeMatches: true, + minMatchCharLength: 2, + threshold: 0.5, + }), + [searchList] + ); useEffect(() => { // if URL has search query,