How to read and modify a state in useEffect IAW 'exhaustive-deps' lint rule

后端 未结 4 983
轮回少年
轮回少年 2021-01-25 19:05

I have a map which has an overlay. I have an effect which, when the underlying data changes, deletes the old overlay and re-draws a new one.

Of note, I\'m using \"

4条回答
  •  渐次进展
    2021-01-25 19:35

    To add onto @DamienFlury's solution, Another technique you can use to remove a constantly changing dependency from the dependency array is to use the useReducer hook. This allows you to decouple your state variables from your effects

    function reducer(state, action){
      if(action.type === 'UPDATE_OVERLAY'){
        return {
         ...state,
         overlay: action.newOverlay,  //update overlay on your state object
        }
      } else {
        return state;
      }
    }
    
    function YourComponent(yourProps){
      const [ state, dispatch ] = useReducer(reducer, initialState);
    
      // Other functions
    
      useEffect(() => {
        // remove the overlay if it is there,
        if (overlay) map.removeOverlays(overlay);    
    
        // Generate the new overlay based on the new data (useCallback function)
        const newOverlay = generateNewOverlay(data)
    
        // this also allows you to decouple your state changes from your effects!
        dispatch({ 
          type: 'UPDATE_OVERLAY', 
          newOverlay,
        });
    
        // Show the new overlay on my map
        map.addOverlays(newOverlay);
    
      }, [dispatch, map, data, generateNewOverlay]);
    
    }
    

    Note that I have added dispatch to the dependency array just as a good practice, You should never lie about your dependencies!. React guarantees the dispatch function to be constant throughout the component lifetime.

提交回复
热议问题