Skip to content

Commit

Permalink
fix: ensure search context provider value is memoized
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan committed Jul 31, 2024
1 parent 8e99272 commit a9c9cce
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ export function SearchWrapper({
* Set shared `onClose` in search context
*/
useEffect(() => {
setOnClose(handleClose)
/**
* When using useState you have to use the function callback version of setState,
* otherwise it'll call your function and set the state to whatever your function return.
*/
setOnClose(() => handleClose)
}, [handleClose, setOnClose])

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {isEqual} from 'lodash'
import {type ReactNode, useCallback, useEffect, useMemo, useReducer, useRef, useState} from 'react'
import {type ReactNode, useEffect, useMemo, useReducer, useRef, useState} from 'react'
import {SearchContext} from 'sanity/_singletons'

import {type CommandListHandle} from '../../../../../../components'
Expand Down Expand Up @@ -28,7 +28,7 @@ interface SearchProviderProps {
* @internal
*/
export function SearchProvider({children, fullscreen}: SearchProviderProps) {
const onCloseRef = useRef<(() => void) | null>(null)
const [onClose, setOnClose] = useState<(() => void) | null>(null)
const [searchCommandList, setSearchCommandList] = useState<CommandListHandle | null>(null)

const schema = useSchema()
Expand Down Expand Up @@ -103,10 +103,6 @@ export function SearchProvider({children, fullscreen}: SearchProviderProps) {
}),
)

const handleSetOnClose = useCallback((onClose: () => void) => {
onCloseRef.current = onClose
}, [])

/**
* Trigger search when any terms (query or selected types) OR current pageIndex has changed
*
Expand Down Expand Up @@ -184,21 +180,20 @@ export function SearchProvider({children, fullscreen}: SearchProviderProps) {
isMountedRef.current = true
}, [dispatch, hasValidTerms, result.hits, terms.query, terms.types])

return (
<SearchContext.Provider
value={{
dispatch,
onClose: onCloseRef?.current,
searchCommandList,
setSearchCommandList,
setOnClose: handleSetOnClose,
state: {
...state,
fullscreen,
},
}}
>
{children}
</SearchContext.Provider>
const value = useMemo(
() => ({
dispatch,
onClose,
searchCommandList,
setSearchCommandList,
setOnClose,
state: {
...state,
fullscreen,
},
}),
[fullscreen, onClose, searchCommandList, state],
)

return <SearchContext.Provider value={value}>{children}</SearchContext.Provider>
}

0 comments on commit a9c9cce

Please sign in to comment.