Search code examples
reactjsreact-nativeuse-effectuse-state

Can't perform a React state update on an unmounted component. This is a no-op


That's the warning in the console,

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.

Here is my code

const [index, setIndex] = useState(0);
  const [refreshing, setRefreshing] = useState(false);
  const refContainer: any = useRef();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const navigation = useNavigation();

  useEffect(() => {
    refContainer.current.scrollToIndex({animated: true, index});
  }, [index]);

  const theNext = (index: number) => {
    if (index < departments.length - 1) {
      setIndex(index + 1);
      setSelectedIndex(index + 1);
    }
  };

  setTimeout(() => {
    theNext(index);
    if (index === departments.length - 1) {
      setIndex(0);
      setSelectedIndex(0);
    }
  }, 4000);

  const onRefresh = () => {
    if (refreshing === false) {
      setRefreshing(true);
      setTimeout(() => {
        setRefreshing(false);
      }, 2000);
    }
  };

What should I do to make clean up?

I tried to do many things but the warning doesn't disappear


Solution

  • setTimeout need to use in useEffect instead. And add clear timeout in return

      useEffect(() => {
        const timeOut = setTimeout(() => {
          theNext(index);
          if (index === departments.length - 1) {
            setIndex(0);
            setSelectedIndex(0);
          }
        }, 4000);
    
        return () => {
          if (timeOut) {
            clearTimeout(timeOut);
          }
        };
      }, []);