From 6bdbbab8611e3dcfe487fec6563af2f605c662f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Thu, 7 Jul 2022 16:45:36 +0200 Subject: [PATCH] fix(React Native): update `` without Effects (#400) --- .../getting-started/src/SearchBox.tsx | 29 ++++++++----------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/react-instantsearch-hooks-native/getting-started/src/SearchBox.tsx b/react-instantsearch-hooks-native/getting-started/src/SearchBox.tsx index 8de8d6e216..0f020fe034 100644 --- a/react-instantsearch-hooks-native/getting-started/src/SearchBox.tsx +++ b/react-instantsearch-hooks-native/getting-started/src/SearchBox.tsx @@ -8,35 +8,30 @@ type SearchBoxProps = UseSearchBoxProps & { export function SearchBox({ onChange, ...props }: SearchBoxProps) { const { query, refine } = useSearchBox(props); - const [value, setValue] = useState(query); + const [inputValue, setInputValue] = useState(query); const inputRef = useRef(null); - // Track when the value coming from the React state changes to synchronize - // it with InstantSearch. - useEffect(() => { - if (query !== value) { - refine(value); - } - }, [value, refine]); + function setQuery(newQuery: string) { + setInputValue(newQuery); + refine(newQuery); + } // Track when the InstantSearch query changes to synchronize it with // the React state. - useEffect(() => { - // We bypass the state update if the input is focused to avoid concurrent - // updates when typing. - if (!inputRef.current?.isFocused() && query !== value) { - setValue(query); - } - }, [query]); + // We bypass the state update if the input is focused to avoid concurrent + // updates when typing. + if (query !== inputValue && !inputRef.current?.isFocused()) { + setInputValue(query); + } return ( { - setValue(newValue); + setQuery(newValue); onChange(newValue); }} clearButtonMode="while-editing"