react-nativereact-hooksscrollviewrefreshuirefreshcontrol

Getting react unmounted hook error with Refresh Control


When I use

const onRefresh = () => {
setRefreshing(true);

   setTimeout(() => {
     setRefreshing(false);
   }, 2000);
};

with RefreshControl in Scroll View and then I get change the page in the middle of refreshing, I get the error below. Normally I can fix this error with a useEffect hook but I can't seem to get it working in any way. Any ideas on how to fix this?

Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application. 
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Solution

  • It's not an error, it's just a warning. I think you could still use a useEffect hook to cancel any running timers when the component unmounts. For convenience you use a React ref to hold a reference to the timeout.

    Example:

    const timerRef = React.useRef();
    
    useEffect(() => {
      // return cleanup function to clear any running timeouts
      return () => clearTimeout(timerRef.current);
    }, []);
    
    const onRefresh = () => {
      setRefreshing(true);
    
      // save current timerId to ref
      timerRef.current = setTimeout(() => {
        setRefreshing(false);
      }, 2000);
    };
    

    I believe that this warning for state updates on unmounted components has been removed in React 18 since it often led to really poor code quality generally