Skip to content

Commit

Permalink
chore(docs): Update "Adding Search with Algolia" guide (#29460)
Browse files Browse the repository at this point in the history
Co-authored-by: gatsbybot <[email protected]>
  • Loading branch information
2 people authored and axe312ger committed May 20, 2021
1 parent 1e064fc commit 48c37e3
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions docs/docs/adding-search-with-algolia.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ You now need to hook up the two components to each other and perform the actual

```jsx:title=src/components/search/index.js
import algoliasearch from "algoliasearch/lite"
import { createRef, default as React, useState } from "react"
import { createRef, default as React, useState, useMemo } from "react"
import { InstantSearch } from "react-instantsearch-dom"
import { ThemeProvider } from "styled-components"
import StyledSearchBox from "./styled-search-box"
Expand All @@ -331,9 +331,13 @@ export default function Search({ indices }) {
const rootRef = createRef()
const [query, setQuery] = useState()
const [hasFocus, setFocus] = useState(false)
const searchClient = algoliasearch(
process.env.GATSBY_ALGOLIA_APP_ID,
process.env.GATSBY_ALGOLIA_SEARCH_KEY
const searchClient = useMemo(
() =>
algoliasearch(
process.env.GATSBY_ALGOLIA_APP_ID,
process.env.GATSBY_ALGOLIA_SEARCH_KEY
),
[]
)

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

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).

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.

`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.

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

0 comments on commit 48c37e3

Please sign in to comment.