ReactJS: Alternatives of setState

Rupen Anjaria
Aug 25, 2017 · 1 min read

Often we rely on ReactJs’s setState assuming internal state will be updated.

However, as ReactJS mentions it is not guaranteed - see this

Secondly, it may run fine between local and UAT, may silently break in Production. That seems not fair to me and made me to search if any alternatives are available?

So, I found these:

  1. Use store (e.g. Redux) instead of internal state: This is by far the best. As it gives full control on the data. Further, as it replaces internal state we can use the state date outside of the component too. For example, we entered new user and required to show recently added user info somewhere else.
  2. Use Async setState: We can create a wrapper method to return promise around setState like:
setStateAsync(state) {
return new Promise((resolve) => {
this.setState(state, resolve)
});
}
async validation(val){
// check validation
if (notValid){
await this.setStateAsync( {
inputText: {
error: true,
"Input is Invalid"
}
})
return false;

}
}async submitCode(){const isValid = await validation(value)
if(!isValid) return false;
}

Source: https://medium.com/front-end-hacking/async-await-with-react-lifecycle-methods-802e7760d802

3. Overloaded setState: Not an alternative, but approach is to use overloaded version of setState. This seems only helpful if you have something to do after setState.

validation(val){
// check validation
if (notValid){
this.setState( {
inputText: {
error: true,
"Input is Invalid"
}
},()=>{return false;}) <-- this will be executee only after state has been updated.
}
}
submitCode(){
const isValid = validation(value)
if(!isValid) return false;
}

Do you know any other alternative ways?

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade