Skip to content

Commit 448061a

Browse files
alowdongatsbybot
and
gatsbybot
authoredMay 6, 2021
chore(docs): Update "Adding Search with Algolia" guide (#29460)
Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>
1 parent ea81d3b commit 448061a

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed
 

‎docs/docs/adding-search-with-algolia.md

+10-4
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ You now need to hook up the two components to each other and perform the actual
313313

314314
```jsx:title=src/components/search/index.js
315315
import algoliasearch from "algoliasearch/lite"
316-
import { createRef, default as React, useState } from "react"
316+
import { createRef, default as React, useState, useMemo } from "react"
317317
import { InstantSearch } from "react-instantsearch-dom"
318318
import { ThemeProvider } from "styled-components"
319319
import StyledSearchBox from "./styled-search-box"
@@ -331,9 +331,13 @@ export default function Search({ indices }) {
331331
const rootRef = createRef()
332332
const [query, setQuery] = useState()
333333
const [hasFocus, setFocus] = useState(false)
334-
const searchClient = algoliasearch(
335-
process.env.GATSBY_ALGOLIA_APP_ID,
336-
process.env.GATSBY_ALGOLIA_SEARCH_KEY
334+
const searchClient = useMemo(
335+
() =>
336+
algoliasearch(
337+
process.env.GATSBY_ALGOLIA_APP_ID,
338+
process.env.GATSBY_ALGOLIA_SEARCH_KEY
339+
),
340+
[]
337341
)
338342

339343
useClickOutside(rootRef, () => setFocus(false))
@@ -362,6 +366,8 @@ The `ThemeProvider` exports variables for the CSS to use (this is the [theming](
362366

363367
The `hasFocus` variable tracks whether the search box is currently in focus. When it is, it should display the input field (if not, only the search icon button is visible).
364368

369+
The `searchClient` variable is [memoized](https://reactjs.org/docs/hooks-reference.html#usememo) to avoid re-creating the Algolia search client when the `Search` component is re-rendered. This is important for performance, as the client caches searches to minimise the number of requests made to Algolia.
370+
365371
`StyledSearchRoot` is the root of the whole component. The React hook `useClickOutside` provides a callback if the user clicks anywhere else on the page, in which case it should close.
366372

367373
`InstantSearch` from [`react-instantsearch-dom`](https://community.algolia.com/react-instantsearch) wraps the search box and search results to orchestrate the search.

0 commit comments

Comments
 (0)
Please sign in to comment.