React hooks useEffect only on update?

前端 未结 8 969
予麋鹿
予麋鹿 2020-12-12 18:53

If we want to restrict useEffect to run only when the component mounts, we can add second parameter of useEffect with [].



        
8条回答
  •  悲&欢浪女
    2020-12-12 19:31

    Took help from Subham's answer This code will only run for particular item update not on every update and not on component initial mounting.

    const isInitialMount = useRef(true);    //useEffect to run only on updates except initial mount
    
    
    //useEffect to run only on updates except initial mount
      useEffect(() => {
        if (isInitialMount.current) {
            isInitialMount.current = false;
         } else {              
             if(fromScreen!='ht1' && appStatus && timeStamp){
                // let timeSpentBG = moment().diff(timeStamp, "seconds");
                // let newHeatingTimer = ((bottomTab1Timer > timeSpentBG) ? (bottomTab1Timer - timeSpentBG) : 0);
                // dispatch({
                //     type: types.FT_BOTTOM_TAB_1,
                //     payload: newHeatingTimer,
                // })
                // console.log('Appstaatus', appStatus, timeSpentBG, newHeatingTimer)
             }
         }
      }, [appStatus])
    

提交回复
热议问题