Home > Net >  How correct change useState ( array, obj and other)?
How correct change useState ( array, obj and other)?

Time:03-14

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])

}

CodePudding user response:

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.

CodePudding user response:

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)
}
  • Related