diff --git a/components/layout.tsx b/components/layout.tsx index ab80033..2bd9c20 100644 --- a/components/layout.tsx +++ b/components/layout.tsx @@ -1,4 +1,4 @@ -import React, { Fragment, PropsWithChildren, useRef, useState } from 'react'; +import React, { Fragment, PropsWithChildren, useState } from 'react'; import Link from 'next/link'; import { useRouter } from 'next/router'; import { Dialog, Popover, Tab, Transition } from '@headlessui/react'; @@ -18,11 +18,12 @@ import { cx, searchClient } from '../utils'; import { navigation, footerNavigation, perks } from '../mock'; import { Autocomplete } from './Autocomplete'; import { AutocompleteItem } from './AutocompleteItem'; +import { useLazyRef } from '../hooks'; export default function Layout({ children }: PropsWithChildren) { const router = useRouter(); const [mobileMenuOpen, setMobileMenuOpen] = useState(false); - const recentSearchesPlugin = useRef( + const getRecentSearchesPlugin = useLazyRef(() => createLocalStorageRecentSearchesPlugin({ key: 'RECENT_SEARCH', limit: 5, @@ -75,7 +76,7 @@ export default function Layout({ children }: PropsWithChildren) { }, }) ); - const querySuggestionsPluginRef = useRef( + const getQuerySuggestionsPlugin = useLazyRef(() => createQuerySuggestionsPlugin({ searchClient, indexName: 'instant_search_demo_query_suggestions', @@ -438,8 +439,8 @@ export default function Layout({ children }: PropsWithChildren) { router.push(`/search/?query=${state.query}`); }} plugins={[ - recentSearchesPlugin.current, - querySuggestionsPluginRef.current, + getRecentSearchesPlugin(), + getQuerySuggestionsPlugin(), ]} /> diff --git a/hooks/index.ts b/hooks/index.ts new file mode 100644 index 0000000..c903ac7 --- /dev/null +++ b/hooks/index.ts @@ -0,0 +1 @@ +export * from './useLazyRef'; diff --git a/hooks/useLazyRef.ts b/hooks/useLazyRef.ts new file mode 100644 index 0000000..c123b9d --- /dev/null +++ b/hooks/useLazyRef.ts @@ -0,0 +1,13 @@ +import { useRef } from 'react'; + +export function useLazyRef(initialValue: () => TValue) { + const ref = useRef(null); + + return function getRef() { + if (ref.current === null) { + ref.current = initialValue(); + } + + return ref.current; + }; +}