Skip to main content

Command Palette

Search for a command to run...

Simplify your React code using shorter setState syntax

Published
6 min read
Simplify your React code using shorter setState syntax
Y

Full Stack Developer | Freelancer | JavaScript | React | Nodejs.

Loves sharing knowledge through technical articles.

Dev.to: https://dev.to/myogeshchavan97

https://linktr.ee/myogeshchavan97

In this article, we will see how we can use the new ES6 shorter syntax which will make the setState call a lot simpler. So Let’s start with some background knowledge.

Take a look at below arrow function.

const getName = () => {
 return "David";
}

The above arrow function has just a single line of code inside it. If there is a single line of code in the arrow function, we can implicitly return it without adding the return keyword so we can make the above code shorter as shown below:

// Example 2
const getName = () => "David";

Example 1 and Example 2 will produce the exact same output. Example 2 is just a shorter syntax of Example 1.

As you know if we have more than one line of code inside the function, we write those statements inside the curly brackets ({}) and we explicitly specify the return statement.

If we are returning an object from a function we write it as

const getObject = () => {
 return {
  name: "David",
  age: 30
 };
};

We can simplify the above code as

const getObject = () => ({
 name: "David",
 age: 30
});

Here we are directly adding the object inside the round brackets ( ) which will implicitly return the object without the need for a return statement.

Now let's see how we can use this in the setState call.

Live Demo: https://codesandbox.io/s/twilight-sea-lnk6z

If you are wondering how the state is written directly inside the component and not in the constructor and why there is no .bind function call added for the event listener, check out my this article which explains it in detail.

Take a look at the setState method inside the handleAddOne method in the above code

this.setState(prevState => {
 return {
  counter: prevState.counter + 1
 };
});

As you can see, this single setState call takes almost five lines of code. It’s also easy to forget adding the return keyword like

// without return keyword
this.setState(prevState => {
 {
  counter: prevState.counter + 1
 };
});

The above setState call of without return keyword will not throw any error even if you missed the return statement but it will not work as expected. So to overcome these issues, We can simplify it as

this.setState(prevState => ({
 counter: prevState.counter + 1
}));

Now it looks shorter.

We can further shorten it, as there is a single statement in the function

this.setState(prevState => ({ counter: prevState.counter + 1 }) );

Wow, we have converted the setState call from five lines to just one line.

It’s perfectly ok to keep it on more than one line, if there is more than one state property we need to set like

this.setState(prevState => ({
  counter: prevState.counter + 1,
  name: 'Jane'
 })
);

Now, Suppose we have an array of numbers in the state and we want to delete all the elements of the array, we use the following setState call

this.setState(() => {
 return {
  numbers: []
 }
});

As always, We can simplify it as

this.setState(() => ({ numbers: [] }) );

To use this shorter syntax of returning an object, there is no need for any configuration changes or any installation. It’s ES6 syntax so it's available by default in create-react-app.

This shorter syntax is common nowadays. You will find it used in almost all the applications that return an object.

That’s it about this article. Hope you learned something new today.

I hope you've been enjoying my articles and tutorials I've been writing. If you found them useful, consider buying me a coffee! I would really appreciate it.

Don’t forget to subscribe to get my weekly newsletter with amazing tips, tricks, and articles directly in your inbox here.

D

Good content, I agree and already use the tips in my code.

The last example can be even shorter (and easy to read) because you are not using the prevState:

this.setState({ numbers: [] });
1
Y

Thank you Darlan Tódero ten Caten.

You're right, the last example can be further simplified as suggested by you because we're not using the previous state value.

1

More from this blog

Yogesh Chavan

125 posts

Full Stack Developer | JavaScript | React | Nodejs. Subscribe to my YouTube Channel: https://www.youtube.com/@codingmastery_dev