When to use useCallback, useMemo and useEffect?

前端 未结 4 851
北恋
北恋 2021-01-30 23:33

What is the main difference between useCallback,useMemo and useEffect. ?.Give examples of when to use useCallback,useMemo and useEffect.

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 00:05

    useEffect

    Gets called when the component mounts, unmounts and any of it's dependencies change.

    Can be used to get data when component is mounted, subscribe and unsubscribe to event streams when component mounts and unmounts (think rxjs).

    const [userId, updateUser] = useState(1);
    
    useEffect(()=>{
      //subscription
       const sub = getUser(userId).subscribe(user => user);
    
    // cleanup
      return () => {
       sub.unsubscribe();
     }
    
    },[userId]) // <-- Will get called again when userId changes
    

    Can also be used for onetime method call which require no cleanup

    useEffect(()=>{
    
      oneTimeData();
    
    },[]); // pass empty array to prevent being called multiple times
    
    

    useCallback

    1. Got functions that you don't want to be re-created on every component render?

    2. Want a function that isn't called on component mount or unmount?

    Use useCallback

    const [val, updateValue] = useState(0);
    
    const Compo = () => {
    
    /* inc and dec will be re-created on every component render. 
       Not desirable a function does very intensive work.
    */
    
    const inc = () => updateValue(x => x + 1);
    const dec = () => updateValue(x => x - 1);
    
    return render() {
       
       
     }
    }
    
    

    useCallback to the rescue

    const [val, updateValue] = useState(0);
    
    const Compo = () => {
    
    const callbackInc = useCallback(() => {
      setCount(currentVal => currentVal + 1);
    }, []);
    
    const callbackDec = useCallback(() => {
      setCount(currentVal => currentVal - 1);
    }, []);
    
    return render() {
       
       
     }
    }
    

    If the argument passed to setCount isn't a function, then the variables you would want useCallback to 'watch' out for must be specified in the dependencies array less there will be no change effect.

    const callbackInc = useCallback(() => {
      setCount(val + 1); // val is an 'outside' variable therefore must be specified as a dependency
    }, [val]);
    

    useMemo

    Doing heavy processing and want to memoize (cache) the results? Use useMemo

    /*
      heavyProcessFunc will only be called again when either val or val2 changes
    */
    const result = useMemo(heavyProcessFunc(val, val2),[val,val2])
    

提交回复
热议问题