1

In our application we are attempting to leverage useEffect to make an api call on cleanup of a component, something like this:

useEffect(() => {
  return () => {
    myAPIFunction(dynamicProp)
    // api call here that leverages a prop
  }
})

The idea here is that we want to make this api call on the tear down of this component. The problem is that as our application progresses dynamicProp changes at the component level, but whenever the api call is made we get the value dynamicProp as whatever it was initialized at.

If we update it it to the following:

useEffect(() => {
  return () => {
    myAPIFunction(dynamicProp)
    // api call here that leverages a prop
  }
}, [dynamicProp])

It does update the prop in the cleanup function but we really only want to call this once on the component cleanup, and this causes the cleanup to fire any time dynamicProp changes.

Is there a solution where we can have dynamicProp be .... dynamic in our cleanup without having to run the cleanup every time dynamicProp changes?

Andrew Kim
  • 3,145
  • 4
  • 22
  • 42
  • Are you saying that in the second case, `myAPIFunction` gets called every time `dynamicProp` changes? – tromgy Jan 21 '22 at 21:29
  • @tromgy correct – Andrew Kim Jan 21 '22 at 21:35
  • does this describe what you're seeing? https://dmitripavlutin.com/react-hooks-stale-closures/ – Nikki9696 Jan 21 '22 at 21:56
  • What indicates in your code that you're performing cleanup? Check for that condition in your useEffect statement. – samuei Jan 21 '22 at 21:57
  • 2
    You can use useRef for dynamicProp and pass .current to api function. – bigless Jan 21 '22 at 22:21
  • You can find detailed discussion of this problem in this [stackoverflow thread](https://stackoverflow.com/questions/55020041/react-hooks-useeffect-cleanup-for-only-componentwillunmount). Check the answer that is using `useRef`. That will work for a case like yours, just like @bigless said. If you want to see a live example, here's the [sandbox](https://codesandbox.io/s/effect-cleanup-unmount-current-state-0cb80?file=/src/App.js) – tromgy Jan 21 '22 at 22:24
  • great, thanks everyone, i'll give it a go, feel free to drop an answer so i can give cred. – Andrew Kim Jan 21 '22 at 22:48
  • Another [example](https://codesandbox.io/s/effect-cleanup-unmount-current-state-forked-4z7bv?file=/src/App.js) (probably closer to what @bigless had in mind). – tromgy Jan 21 '22 at 22:48
  • This has been answered in that thread, so IMHO no credit is due here – tromgy Jan 21 '22 at 22:49

0 Answers0