What is the difference between these two state updating functions and what is the recommended approach? Both functions work fine in my application.
Option 1
const [profile, setProfile] = useState<{name: string, age: number}>({
name: 'John Doe',
age: 28,
});
setProfile((prevState) => {
return {
...prevState,
age: profile.age 100,
}
});
Option 2
const [profile, setProfile] = useState<{name: string, age: number}>({
name: 'John Doe',
age: 28,
});
setProfile({
...profile,
age: profile.age 100,
});
CodePudding user response:
Normally each time you want to update your state based on your previous state you should use the functional way of updating the state. It makes sure that the current state you are passing in, is the 'last version' one.
When you want to set a state based on a different value, not depending on previous state, you can set the state directly without using the functional update.
It is pretty well explained with examples in the documentation:
https://reactjs.org/docs/hooks-reference.html#usestate
the documentation includes this great example:
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount 1)}> </button>
</>
);
}
Note that unlike setState in a class component, useState doesn't merge update, Also from the documentation:
Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:
const [state, setState] = useState({});
setState(prevState => {
// Object.assign would also work
return {...prevState, ...updatedValues};
});
Option 2 will work in most cases because you rarely have a change of state appearing before another change of state, but it can happen in more complex cases or using useEffect or setTimeout functions and in this case the functional update is compulsory.
CodePudding user response:
They are basically the same, but the second approach is used when you can't assure that you have the updated value of your state on hand. For example in a setTimeout or useEffect callback
