Chandrika
Chandrika

Reputation: 141

How to conditionally update state based on previous state in react functional component?

So, I want to do the following,

const [value, setValue] = useState({})
const updateName = (name)
setValue(previousState => {
  if (/*check some conditions*/) {
    // dont update the state
  } else {
    return { /* some new state */ }
  }
});

Is there anyway how can i achieve it?

Upvotes: 9

Views: 25413

Answers (2)

Rodrigo Ibarra
Rodrigo Ibarra

Reputation: 325

You can try with something simple like:

setValue(!value)

That will just change a boolean state, passing from false value to true value and vice versa.

I hope it can help.

Upvotes: 0

cbdeveloper
cbdeveloper

Reputation: 31365

You are almost there.

const [value, setValue] = useState({})

setValue((prevState) => {
  if (condition to not update) {
    return prevState;
  } else {
    return newState;
  }
});

You don't necessarily need to do it from the setValue call. You can also do it like this:

const updateSomething = () => {
  if (shouldUpdate)
    setValue(newState);
}

Upvotes: 16

Related Questions