ReactJS: Alternatives of setState
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:
- 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.
- 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?