How to stop memory leak in useEffect hook react

后端 未结 3 1733
孤城傲影
孤城傲影 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 (
        <ReactTable onFetchData={setFilter} /* other props omitted */ />
      );
    }
    
    0 讨论(0)
  • 2021-02-04 06:04

    The other answers work of course, I just wanted to share a solution I came up with. I built this hook that works just like React's useState, but will only setState if the component is mounted. I find it more elegant because you don't have to mess arround with an isMounted variable in your component !

    Installation :

    npm install use-state-if-mounted
    

    Usage :

    const [count, setCount] = useStateIfMounted(0);
    

    You can find more advanced documentation on the npm page of the hook.

    0 讨论(0)
  • 2021-02-04 06:23

    For some other folks I had a similar issue (memory leak) and my issue was that I was calling a hook inside a hook in my case useEffect

    0 讨论(0)
提交回复
热议问题