'How correct change useState ( array, obj and other)?

I'm learning React and trying to figure out how to properly change the state in functional components. Can you please tell me if there is a difference between these two options? And if there is, which one is preferable to use in work? Thanks!

 const addNewTaskInState = (subtitle: string) => {
     setTodoListStateArray((todoListStateArray) => {
         const newTask = addNewTask(subtitle);
         return [...todoListStateArray, newTask]
     })

 }

const addNewTaskInState = (subtitle: string) => {
    const newTask = addNewTask(subtitle);
    setTodoListStateArray([...todoListStateArray, newTask])

}


Solution 1:[1]

The first approach name updater function you can read here Updating state based on the previous state

And your question is answer below of that sections:

  1. Can you please tell me if there is a difference between these two options?

In most cases, there is no difference between these two approaches

  1. which one is preferable to use in work?

If you prefer consistency over slightly more verbose syntax, it’s reasonable to always write an updater if the state you’re setting is calculated from the previous state. If it’s calculated from the previous state of some other state variable, you might want to combine them into one object and use a reducer.

Solution 2:[2]

I think 2nd one is more efficient you can use it. if you want to adopt another approach have a look at this code

const [state, setState] = useState([])

function SetMyState (obj) {
     let auxiliaryArray = [...state]
     auxiliaryArray.push(obj) 
     setState(auxiliaryArray)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 zain ul din