KFunk
KFunk

Reputation: 3152

react-hooks/exhaustive-deps following rule causes bug. Not all dependencies should be watched?

I've got a search component that can be triggered two ways. One by a user typing (debounced), and one by a button to retry. react-hooks/exhaustive-deps's suggestion actually causes a bug for me, as watching searchTerm fires both effects, when I only want the first to fire. Is there another approach that I should take?

export default function Search(props) {
  const [searchTerm, setSearchTerm] = useState('')
  const [retryCounter, setRetryCounter] = useRetryCounter() // number (int) of manual retries

  function search() { ... }

  const debouncedSearch = useRef(lodash.debounce(search, 300, { maxWait: 500 })).current

  useEffect(() => {
    debouncedSearch(searchTerm)
  }, [searchTerm, debouncedSearch])
  // when `searchTerm` changes, a user has typed into an <input />, so do a debounced search

  useEffect(() => {
    // i want to continue using the `searchTerm` provided by the user preivously
    search(searchTerm)
  }, [retryCounter])
  // if i add `searchTerm` as a dep, then BOTH useEffects fire, and `search` gets fired twice.
  // therefore, i explicitly want to ignore changes to `searchTerm` here

  ...
  
  return (
    <>
      <input value={searchTerm} onChange={e => setSearchTerm(e.target.value)} />
      <button onClick={setRetryCounter}>retry</button>
    </>
  )
}

I also noticed on the official discussion of this rule that @StevenMyers32's question was not addressed (he has a codesandbox example), and his example seems to be a similar problem of "if i include this dependency, useEffect will incorrectly fire".

Upvotes: 0

Views: 261

Answers (0)

Related Questions