react-nativereact-hooks

React Native:How to detect function component will unmount?


My RN 0.62.2 app needs to automatically save page data just before the function component unmounts. The idea is that when the user close the page (detecting losing focus may not work here since user may zoom in image in modal screen), then the save (to backend server) is automatically triggered. Since it is function component, how to know when the component will unmount?

Here is the sample code of a function component shall do:

    const MyCom = () => {
    
      //do something here. ex, open gallery to upload image, zoon in image in `modal screen,  enter input`
    
      if (component will unmount) {
        //save the data by sending them to backend server
      }
    }

The useEffect triggers with every rendering and will have performance issue if keep saving to backend server with each and every rendering. The auto save only happens once just before the component unmount. User may click Back or Home button to leave the page.


Solution

  • Yoı must use useEffect for componentWillUnmount in functional components.

    const MyCom = () => {
    
      //do something here. ex, open gallery to upload image, zoon in image in 
    
      useEffect(() => {
        // Component Did Mount
    
        return () => {
          // ComponentWillUnmount
        }
      },[])
    
      return(/*Component*/)
    }