I saw React codes generally use arrow function for setState(). However, for useState(), I see that they just put a number, eg useState(0) instead of arrow function, ie useState( () => 0 )
Are there any reasons why I would want to use an arrow function in useState ? Is it alright to use only arrow functions for ALL React hook regardless, including initialising the hook. Any gotcha ? Thanks very much.
CodePudding user response:
For your simple case it does not matter. You are just making an extra function call which returns a value without any computation.
But in case your initial state is a result of an expensive computation you can use a function.
Using the below
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});
instead of
const [state, setState] = useState(someExpensiveComputation(props));
matters greatly.
The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded.
So even when your value is disregarded you would be making that expensive computation. You can provide a function in your useState which will only run on the very first render, like in the second case above. [Link](The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded.)
CodePudding user response:
As far as I know, the arrow functions in state setter permit use the previous state. For example:
const [message, setMessage] = useState('hello ')
... # Receive data from a form or API, etc.
let name = 'Richard'
setMessage(old_state => old_state name) # 'hello Richard'
This way, you can create counter or reuse some data of the previous state.
Use setState(new_vale)
is totally correct for reset the value.