0

When moving pages through NavLink, most of the memory leak warnings disappeared when the cleanup function was used. However, when using react-redux, a memory leak warning occurs. How do I create a cleanup function to get rid of this warning message? My code is here. For this code, using useState instead of useDispatch made the warning go away.

function List() {
  const [isShow, setIsShow] = useState(false);
  const dispatch = useDispatch();
  const list = useSelector((state) => state.list);

  useEffect(() => {
    async function load() {
      await dispatch(loadlist());
      setIsShow(true);
    }
    let clean = true;
    setIsShow(false);
    if (clean) load();
    return () => (clean = false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (isShow) return <Table data={list} />;
  else return <Loading />;
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
extradeck
  • 366
  • 1
  • 5
  • 19
  • 1
    Do you know what specific code is causing the "leak"? It typically occurs when you enqueue a state update in a asynchronous callback and a component is later unmounted before the callback is invoked. I'm guessing this code is updating the `isShow` state and unmounting the `Table` component while the `Table` component is possible loading/setting some state? – Drew Reese Nov 09 '21 at 05:01
  • @DrewReese Seeing the comment and modifying `setIsShow(true)` to `if(clean) setIsShow(true)` solved the problem. Thank you. – extradeck Nov 09 '21 at 06:02
  • 1
    Ah, the old `isMounted` trick. Yeah, this will work in most cases. I read recently a blog snippet from Gaearon regarding this and that this warning will likely be removed in React v18 since state updates for unmounted components are ignored anyway. – Drew Reese Nov 09 '21 at 06:09

0 Answers0