Why does the 'useState' hook invoke the initial state when it's a function reference?

前端 未结 1 1202
野趣味
野趣味 2021-01-17 22:21

React has a hook called useState, which is used when adding state to functional components.

The Hooks API Reference states:

useState

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 22:29

    This is documented here:

    Lazy initial state

    The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded. If the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render:

    const [state, setState] = useState(() => {
      const initialState = someExpensiveComputation(props);
      return initialState;
    });
    

    Passing a callback to setState also calls the callback, but for a different reason:

    Functional updates

    If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value. Here’s an example of a counter component that uses both forms of setState:

    function Counter({initialCount}) {
      const [count, setCount] = useState(initialCount);
      return (
        <>
          Count: {count}
          
          
          
        
      );
    }
    

    0 讨论(0)
提交回复
热议问题