useState
adds state storage capability to React functional components; each component can maintain its own state using useState
.
This is how you define a state in a component:
import React, { useState } from 'react';
export function MyComponent() {
const [count, setCount] = useState(0);
const handleIncrease = () => setCount(c => c + 1);
return (
<div>
<button onClick={handleIncrease}>Increase</button>
<p>Count: {count}</p>
</div>
);
}
The key pitfall about useState
is often the argument that goes into it. The argument to useState
can be in either of the two shapes below:
The key point about the argument to useState
is that it is only taken in at the component's initial render. For example, if you are passing a component prop as argument, useState
will take the prop value only once; it won't update the state value if the prop value changes. If you need the state value to change upon prop change, then you would need a useEffect
block and set the state in it.
On the other hand, if initial value of the state requires an expensive calculation, you would want to pass a function argument to useState
as it will only run once to set the state's initial value.
The output of useState
is an array: const [count, setCount] = useState(0);
. The state is the first argument, count, and the setter is the latter. The setter can be used anywhere in the component to update its state; the argument to setter can be in two forms:
The setter doesn't update the state value immediately, it queues the update; that's the reason you need to use function argument if you need the previous state to set the current state. As in the example above, we pass a function argument to setCount
, React calls the setter's argument function with the most recent value of the state.
The other useState
pitfall is often about how it triggers a re-render. It will trigger a re-render only if the value passed to setter is different than the state value. If the state is an object/array, a new object/array must be created by spreading the previous state with the changes applied on the spread. React will replace the existing state with the new object/array.
© 2024 Near Max Ltd
Near Max Ltd, kompaniya bi têkildarî 09222812 li Îngiltere û Walesê tê rekînandin. Navnîşa tê rekînandinê: Highwoods, Chinnor Hill, Chinnor, Oxfordshire, OX39 4BD.
Highwoods, Chinnor Hill, Oxfordshire, OX39 4BD, United Kingdom