1

I'm a junior frontend developer and I'm a little bit confusing about the difference between

  1. 'prev'
  2. 'prevstate'
  3. 'prevState'

in useState hooks. I found them maybe all the same referencing to the state before, and I create a counter example for testing it out.

codesandbox: https://codesandbox.io/s/react-counter-8snzou?file=/src/App.js

Can somebody give me an explanation of the difference or if there's no difference, why would there be three kinds of prevState?

I expecting someone could give me a good explanation of prevState in useState hooks. Thank you for any help you can provide.

stevetanus
  • 13
  • 5

1 Answers1

0

They all are the same. The setState(setCount) function expects a function as a parameter.

Basically setState works as follows

const setState = (func) => {
    let state = ... // currentState
    state = func(state); // Modefy current state
}

So you update the value of the state to be the value returned from the function you defined when calling the useState function. In your case, you are only repeating the same thing by calling useState again and again

Shakya Peiris
  • 504
  • 5
  • 11
  • Thanks for your explanation, I get more clear about setState could also put in function as parameter. Then the function could modify the previous state. – stevetanus Jan 16 '23 at 09:32