0

I am trying to use reactHook from an example like this;

const [newAccount, setNewAccount] = useState(true);
const toggleAccount = () => {
    setNewAccount((prev) => !prev);
}

newAccount is to tell whether the user already has on account, and made an event to function to toggle the status of NewAccount.

I thought in setNewaccount ,I should put a value as param like; setNewAccount(!newAccount); It works, but the example puts an arrow function ((prev)=>!prev);,and still it does work too. I am quite confused as why it works.

In my opinion, by using setNewAccount like that doesnt newAccount become a function {{prev)=>!prev}, not the boolean value that I originally thought?

Inu Jung
  • 150
  • 2
  • 9
  • 6
    State setters in React can take callback functions where the argument of the function is the previous stateful value. This can be helpful if you want to ensure the state setter is run on the most current version of state rather than having closure around the state in its outer scope – Nick Jul 27 '21 at 12:26
  • You can pass a value or a function to `setState`, the second parameter returned by `useState`. If you pass a value, you set the updated value and if you pass a function, you get `prevState` as its function parameter. it is recommended to use function approach if you are using prevState while updating state – Xaarth Jul 27 '21 at 12:26
  • related: https://stackoverflow.com/questions/55510565/do-we-still-need-functional-setstate-way-in-react-hooks – Xaarth Jul 27 '21 at 12:28
  • I was also searching for the same doubt, thank you @Nick best explanation. – Mohit Kushwaha Jul 28 '21 at 11:02
  • in your last paragraph you meant {(prev)=>!prev} – Lionel-fr Nov 26 '22 at 22:47

0 Answers0