search bar idle time react js

Solutions on MaxInterview for search bar idle time react js by the best coders in the world

showing results for - "search bar idle time react js"
Beryl
07 Oct 2020
1How about a custom hook?
2
3import {useEffect, useRef, useState} from "react";
4
5export default function useSearchInputState(searchHandler) {
6  
7  // to prevent calling the handler on component mount
8  const didMountRef = useRef(false);
9
10  const [searchValue, setSearchValue] = useState(null);
11
12  useEffect(() => {
13    let delayDebounceFn;
14
15    if (didMountRef.current) {
16      delayDebounceFn = setTimeout(searchHandler, 600)
17    } else {
18      didMountRef.current = true;
19    }
20
21    return () => clearTimeout(delayDebounceFn);
22  }, [searchValue]); // eslint-disable-line react-hooks/exhaustive-deps
23
24  return [searchValue, setSearchValue];
25
26}
27Usage:
28
29function MyComponent(props) {
30
31  const [searchValue, setSearchValue] = useSearchInputState(() => {
32    resetData(searchValue ?? null, selectedFilterPos); // replace with your code
33  });
34
35  return (
36    <input className="Search"
37           onChange={e => setSearchValue(e?.target?.value ?? null)}
38      />
39  );
40}