Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent React Hook's useEffect from fetching data multiple times

The example below shows how my use of useEffect() causes multiple Ajax requests. On the initial rendering of the component, this request is made twice. If the tag is changed, this request is made twice.

I can use some kind of internal state variables to track whether I have already fetched. Or I can create a kind of stack where I push on potential requests of a certain type, then before returning pop the stack and run the final request. But all of these seem like a hack.

(If it helps, the application is quite a bit larger, and I am using redux. Is a broader solution something like redux-saga's cancellation?)

const Thing => () => {
  const [tagId, setTagId] = useState(null)
  const [query, setQuery] = useState('')

  useEffect(() => {
    doSomeAjaxAndUpdateResults()
    setQuery('')
  }, [tagId])

  useEffect(() => {
    doSomeAjaxAndUpdateResults()
  }, [query])

  // ... bunch of extra effects with similar dependencies.
}
like image 321
rooney Avatar asked Feb 06 '26 10:02

rooney


1 Answers

You can just combine both internal state variables into one useEffect hook and then if one change you can do doSomeAjaxAndUpdateResults

const Thing = (prop) => {
  const [tagId, setTagId] = useState(null)
  const [query, setQuery] = useState('')

  useEffect(() => {
    doSomeAjaxAndUpdateResults()
    setQuery('')
  }, [tagId, query])

  return ...;
}

Here's the live example that also relies on props being passed over: https://stackblitz.com/edit/react-wzmxmj

First render is with initial value, second render is with props being passed over and then subsequent props change will trigger one call each.

like image 62
Rikin Avatar answered Feb 12 '26 09:02

Rikin