To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function

后端 未结 6 914
无人及你
无人及你 2021-02-03 23:18

I have this code

import ReactDOM from "react-dom";
import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Route         


        
6条回答
  •  旧时难觅i
    2021-02-03 23:40

    useEffect will try to keep communications with your data-fetching procedure even while the component has unmounted. Since this is an anti-pattern and exposes your application to memory leakage, cancelling the subscription to useEffect optimizes your app.

    In the simple implementation example below, you'd use a flag (isSubscribed) to determine when to cancel your subscription. At the end of the effect, you'd make a call to clean up.

    export const useUserData = () => {
      const initialState = {
        user: {},
        error: null
      }
      const [state, setState] = useState(initialState);
    
      useEffect(() => {
        // clean up controller
        let isSubscribed = true;
    
        // Try to communicate with sever API
        fetch(SERVER_URI)
          .then(response => response.json())
          .then(data => isSubscribed ? setState(prevState => ({
            ...prevState, user: data
          })) : null)
          .catch(error => {
            if (isSubscribed) {
              setState(prevState => ({
                ...prevState,
                error
              }));
            }
          })
    
        // cancel subscription to useEffect
        return () => (isSubscribed = false)
      }, []);
    
      return state
    }
    

    You can read up more from this blog juliangaramendy

提交回复
热议问题