Which one's better: setState(prevState=>( { ...prevState, newValue } )) or setState( {..state, newValue} )

Viewed 34

So there are 2 methods of updating a part of the useState variable like this one:

const [state, setState] = useState({
    field1: [0, 33, 92],
    field2: ['asddsa', 'asd'],
    field3: ['i', 'd', '0']
})

setState(prevState => ({
    ...prevState,
    field4: [3.14, 2.7183]
}))

// OR

setState({
    ...state,
    field4: [3.14, 2.7183]
})

Which one's better to use? I've encountered that in some cases the variable 'state' gives an older value while using the 2nd method.

0 Answers
Related