-1

I'm new to react and javascript I just wanna ask if there would be a problem if I will be coding this

let [value, setValue] = useState(0);

// combined with this:

setValue((value += 1));

//instead of doing this:

const [value, setValue] = useState(0);

//combined with this:

setValue((prevState) => {
        return prevState + 1;
      });

Thankkkk you so mucccch!

StarOrbit
  • 15
  • 1
  • 4
  • Check this https://stackoverflow.com/questions/50837670/reactjs-setstate-previous-state-is-the-first-argument-props-as-the-second-argum – ishaba Jul 28 '21 at 04:13
  • 1
    Have you had any problems coding the first way? – smac89 Jul 28 '21 at 04:18
  • No .. it works fine as the setValue((prevState) => { return prevState + 1; });. I just wanna know if the the first way could be a substitute – StarOrbit Jul 28 '21 at 06:07

1 Answers1

1

This is perfectly fine, no issue with it.

setValue((prevState) => {
        return prevState + 1;
      });

You can also write setValue(prevState=>prevState+1) - a short form of getting previous state and updating it.

setValue((value += 1)); this is valid but a better approach would be to take the previous state and update with new.

Sharad Pawar
  • 290
  • 1
  • 2
  • 16
  • Why is `setValue((value += 1));` not valid? – user3532758 Jul 28 '21 at 04:32
  • @user3532758 indeed a valid but here idea is to take the previous state and update with a new one and setValue((value += 1)) doesn't take prev state. Edited my comment which created confusion. – Sharad Pawar Jul 28 '21 at 04:56