Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(docs): Update "Adding Search with Algolia" guide #29460

Merged
merged 2 commits into from
May 6, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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