Use Effect Cleanup

What is useEffect cleanup about?

Thuto’s description helped me grok it much better than the docs:

Usually with your clean up function in your useEffect, you would be deleting (lack of a better word) and canceling any async calls which might come back and find that the component no longer exists.

Perfectly illustrates how a memory leak can happen

React Native Component/Screen unmounting

  • in react-native, screens don’t always unmount. This is dependent on how you do your routing.
    • be weary of this when relying on useeffect cleanup
  • I think components do unmount, I don’t have a deterministic description of this yet

🔥: Here’s how you can quickly check if the file you’re working on unmounts or not

useEffect(() => {
return () => console.log('I just unmounted')
}, [])

Things you might want to clean up

  • Event listeners
  • DB connections
  • web socket connections
  • timers like setInterval

useEffect alternatives

  • use an event handling function instead
  • React Query pattern is good
    • const {data, error, isLoading} = someFunction()
    • this declaration is done at the top level of the component
    • someFunction() can be a hook, util function, or an abstraction that exists only in the component calling it
    • does this work well with async?