1

I'm confused about whether I should be using a setState callback or the useEffects hook when updating state in my application. On my dashboard, I have a loggedInUser object, which has these fields

cashAssets
stockASsets
bondAssets

From my dashboard, I have components with execute transaction buttons, which work similarly,

<TransactionButton type={type} onClick={handleOnClick} />

When someone executes a transaction, that could affect all of the three above fields for a loggedInUser. From my dashboard component, I'm uncertain about whether I should set these 3 fields of my user object as three state variables and further how should they be updated -- using a setState callback or setting them up via useEffects, e.g.

  useEffect(() => {
    // Add logic to update all three
  }, [cashAssets, stockAssets, bondAssets]);

or should I be treating the loggedInUser object as a state variable?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
satish
  • 703
  • 5
  • 23
  • 52

1 Answers1

1

You do not need to implement useEffect to update state values in response to an event. You can update the state in event handler itself.

Since you want to update all three fields of the state object you can just call setState update function with the new object with updated fields or if the fields depend on previous values then use functional setState

const handleClick = () => {
   // name your setState whatever you call it from useState
   setState(prev => ({
      ...prev,
      cashAssets: // new value here,
      stockASsets: // new value here
      bondAssets: // new value here
   })
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Thank you. Am I assuming then, that even though all three fields are part of my loggedInUser object, I should split them out separately as state variables from my loggedInUserObject? – satish May 11 '20 at 17:46
  • No, you do not need to split them out inside individual state, you can update a state object like I showed above – Shubham Khatri May 11 '20 at 17:52