Sole
Sole

Reputation: 3340

When to update state based on previous state in useState hook in React/Typescript

I have seen quiet a few examples on how to update state based on previous state, but I don't see much explanation on when to update state based on previous state, most examples use a counter example, but what if I was setting a object in state, would this still be based on the previous value or can I just update the state. e.g

const exampleData = [
    {
       text: 'Example name',
       value: 1
    },
    {
       text: 'Example name 2',
       value: 2
    }
]

  const [asset, setAsset] = useState(exampleData[0]);

  const handleClick = (event) => {
      setAsset(event.target.value) 
  }

So in the example I am updating the state in the handleClick function, but would I need to update it based on the previous value or not?

Upvotes: 0

Views: 1270

Answers (1)

Ali Yaghoubi
Ali Yaghoubi

Reputation: 1280

If you want to access previous state, avaiable in setState action

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

const handleClick = () => {
    setState(prev => !prev); // true
    setState(prev => !prev); // false
}

Notice: setState is async action

Upvotes: 1

Related Questions