React hook equivalent to callback function after setting state

前端 未结 2 640
执笔经年
执笔经年 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

    You can use useEffect/useLayoutEffect to achieve this:

    const SomeComponent = () => {
      const [count, setCount] = React.useState(0)
    
      React.useEffect(() => {
        if (count > 1) {
          document.title = 'Threshold of over 1 reached.';
        } else {
          document.title = 'No threshold reached.';
        }
      }, [count]);
    
      return (
        

    {count}

    ); };

    If you are looking for an out of the box solution, check out this custom hook that works like useState but accepts as second parameter a callback function:

    import useStateWithCallback from 'use-state-with-callback';
    
    const SomeOtherComponent = () => {
      const [count, setCount] = useStateWithCallback(0, count => {
        if (count > 1) {
          document.title = 'Threshold of over 1 reached.';
        } else {
          document.title = 'No threshold reached.';
        }
      });
    
      return (
        

    {count}

    ); };

    It can be installed via npm install use-state-with-callback

提交回复
热议问题