Skip to content

Commit

Permalink
refactor: use lazy refs for Autocomplete plugins (#9)
Browse files Browse the repository at this point in the history
This uses lazy refs instead of standard refs to lazily instantiate
plugins and ensure they only get called once.

This method is recommended over `useMemo` because it's not designed to
retain values, and could recompute arbitrarily in the future (see
facebook/react#14490 (comment)).
  • Loading branch information
sarahdayan authored Sep 13, 2022
1 parent d8005d7 commit f97f9f4
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
11 changes: 6 additions & 5 deletions components/layout.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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,
Expand Down Expand Up @@ -75,7 +76,7 @@ export default function Layout({ children }: PropsWithChildren) {
},
})
);
const querySuggestionsPluginRef = useRef(
const getQuerySuggestionsPlugin = useLazyRef(() =>
createQuerySuggestionsPlugin({
searchClient,
indexName: 'instant_search_demo_query_suggestions',
Expand Down Expand Up @@ -438,8 +439,8 @@ export default function Layout({ children }: PropsWithChildren) {
router.push(`/search/?query=${state.query}`);
}}
plugins={[
recentSearchesPlugin.current,
querySuggestionsPluginRef.current,
getRecentSearchesPlugin(),
getQuerySuggestionsPlugin(),
]}
/>

Expand Down
1 change: 1 addition & 0 deletions hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './useLazyRef';
13 changes: 13 additions & 0 deletions hooks/useLazyRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useRef } from 'react';

export function useLazyRef<TValue>(initialValue: () => TValue) {
const ref = useRef<TValue | null>(null);

return function getRef() {
if (ref.current === null) {
ref.current = initialValue();
}

return ref.current;
};
}

0 comments on commit f97f9f4

Please sign in to comment.