How to reduce setState and code size.

SHUBHAM GAUTAM
2 min readFeb 25, 2018

--

When react landed to dev everyone rushed towards it, they wanted to move everything in react. Soon, every company start migrating their apps to react (which is kinda good for us). Don’t worry this article is not about some heavy glitch in react which can cause your application unusable in near future :).

I am writing this post cause there is a small habit i have seen in lot of dev’s sometimes newbie’s sometimes the skilled one’s one method with many setState’s. Which keep me thinking why there is need of it.

for e.g.

function eg(){ if(condition1) {
//newstate creation code will go here
this.setState(newState);
}
if(condition2) {
this.setState(newState);
}
if(condition3) {
this.setState(newState);
}
}

Nothing is actually wrong with above code, user might to update different state value inside each if. Best case scenario everything work accordingly and one setState will be called in each execution, but we should code for failure and in worst case user might actual calling three setState.

Optimising the setState

here is the way to optimize above snippet

function eg(){let functionStateObj = {};
if(condition1) {
//newstate creation code will go here
functionStateObj.val1={
$set : val1;
}
}
if(condition2) {
functionStateObj.val2={
$set : val2;
}
}
if(condition3) {
functionStateObj.val3={
$set : val]3;
}
}

const newState = update(this.state, functionStateObj);
this.setState(newState);
}

What is changed?

Nothing much, instead of calling individual setState i am creating a dynamic update object for react immutability helper. Immutability helper is needed to alter my state object and generate a newState object without affecting my original state. Updating state directly is a big no no.

Above technique can be further optimized to a level where every state component will have just one common state update.

function updateCompState(newStateObj) {
const newState = update(this.state, newStateObj);
this.setState(newState);
}

That’s all folks !!!

--

--

No responses yet