How to stop memory leak in useEffect hook react

后端 未结 3 1734
孤城傲影
孤城傲影 2021-02-04 05:46

I am using Effect hook to fetch the datas from server and these data are passed to the react table there i have used the same api call to load the next set of datas from server.

3条回答
  •  深忆病人
    2021-02-04 05:58

    With useEffect you can return a function that will be run on cleanup. So in your case, you'll want something like this:

    useEffect(() => {
      let unmounted = false;
    
      setPageLoading(true);
    
      props
        .dispatch(fetchCourses())
        .then(() => {
          if (!unmounted) {
            setPageLoading(false);
          }
        })
        .catch((error: string) => {
          if (!unmounted) {
            toast.error(error);
            setPageLoading(false);
          }
        });
    
      return () => { unmounted = true };
    }, []);
    

    EDIT: if you need to have a call that's kicked off outside of useEffect, then it will still need to check an unmounted variable to tell whether it should skip the call to setState. That unmounted variable will be set by a useEffect, but now you need to go through some hurdles to make the variable accessible outside of the effect.

    const Example = (props) => {
      const unmounted = useRef(false);
      useEffect(() => {
        return () => { unmounted.current = true }
      }, []);
    
      const setFilter = () => {
        // ...
        props.dispatch(fetchCourses()).then(() => {
          if (!unmounted.current) {
            setLoading(false);
          }
        })
      }
    
      // ...
      return (
        
      );
    }
    

提交回复
热议问题