React hook equivalent to callback function after setting state

前端 未结 2 648
执笔经年
执笔经年 2021-02-07 07:03

In react (before hooks) when we set state we could call a function after state had been set as such:

this.setState({}, () => {//Callback})

W

2条回答
  •  再見小時候
    2021-02-07 07:22

    The useEffect hook can be used to invoke a function when some state change. If you pass it currentRange in an array as second argument, the function will only be invoked when currentRange change.

    You can also create your own custom hook that uses the useRef hook to keep track of if it's the first time the effect is being run, so that you can skip the first invocation.

    Example

    const { useRef, useState, useEffect } = React;
    
    function useEffectSkipFirst(fn, arr) {
      const isFirst = useRef(true);
    
      useEffect(() => {
        if (isFirst.current) {
          isFirst.current = false;
          return;
        }
    
        return fn();
      }, arr);
    }
    
    function App() {
      const [currentRange, setCurrentRange] = useState("24h");
    
      useEffectSkipFirst(
        () => {
          console.log("hi");
        },
        [currentRange]
      );
    
      return (
        
      );
    }
    
    ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题