Clean Up Your React Code

Mariam Kochumian
JavaScript in Plain English
6 min readMar 3, 2022

“Even if you’re writing code only for yourself, with no possibility of it being used in any way by anyone else, your future self will thank you if you write clear code.” ~ Clean Code in JavaScript (James Padolsey)

Immutability

React has a declarative programming approach. So to clean up our code, it is important to understand what declarative programming means and follow functional programming style.

What does immutability mean?

Basically, an immutable value is a value that cannot be changed. Consequently, instead of mutating the value of the original data, we need to create a new copy and return it. This way of working with values is called immutability.

Let’s look at a simple example:

The ‘addFruit’ function changes the value of the given array.

We need to change the function as follows:

The ‘addFruitPure’ function returns a new array without affecting the original.

The function that treats the input value as immutable calls the pure function.
The pure function has no side effects and if we call this function twice, we get the same result.

These concepts are used very often, especially when you work with libraries such as Redux.

Keep your code DRY

“Don’t repeat yourself (DRY) is a principle of software development aimed at reducing repetition of software patterns, replacing it with abstractions.”
~ Wikipedia

Duplicating the code usually leads to problems and unexpected results because it impacts code maintainability and makes debugging very hard.

React can help us to avoid code duplications with reusable components.

Let’s dive into an example. Suppose we have a ‘Create User’ form and for creating a user we must select a country from dropdown box, and also we have a ‘Users List’ component in our application where we can filter our users by their role.

Inside the render method, we loop through the countries, and we map each option into a <li> element.

Again we loop through the roles, and for each one display the title instead of the name.

Let’s look at these components in more detail:

Both of them have a title — Country and Role, state for selected option and handleClick function which triggers when onClick event is fired.

The difference is that the option value, in UsersList, is title(role.title) rather than name(country.name).

So the main requirement of our component is to display the title of dropdown, map through the options list and handle onClick event.

The ‘Dropdown’ component receives the props, displays the title, and iterates over the collection.

We can now rewrite our components:

Great, now we can use the ‘Dropdown’ component many times within the app just by passing the right props. Perhaps there is a new requirement to change the style or implement additional functionality for dropdown, we can make the change at one single point, and all the components that are using it will be aware of modification.

Don’t forget a KEY

React has different techniques to optimize the rendering of the component.

“Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.” ~ reactjs.org

Thus, using the key attribute helps to avoid unnecessary re-renderings in the application.

Let’s delve into the code:

The simple component above displays a list of users and the ‘Add User’ button which inserts a new user as a first element to the list causing a new render of the component.

If we run the code, we will see (inside the browser DevTools) that React, instead of just adding the new element, will mutate the values of the previous users and will add a new item at the end of the list (because React will figure out that elements are different as they were at first render) .

Fortunately, React gives developers a tool to improve the rendering performance of our components.

Now, we can change the render method and add key attribute on each element:

If we run the code again, we will see that the behavior of our component is the same. However, if we open the browser DevTools we will find something different — React does not mutate the values of the previous elements, because it knows which element is the new one and which element has to be updated.

Last but not least, you can pass an item’s index as a key, if the items are never reordered.

Let’s again create ‘Users List’ component but change the render method in the following way:

We added an input field to write an email for each user.

Running the code, and after writing emails let’s click on the button to add a new user to the beginning of the list.

We will get an unexpected behavior, as shown in the following screenshot:

The full names of users will shift down while the input fields will not change their values. This is because React thinks that we changed the values of the first two users (because of 0 and 1 key values) and added a new element with index 2.

ESLint

ESLint is an open-source JavaScript linting utility. It can help us to avoid syntactical errors, check the correctness of our code as soon as we type it and finally enforce common coding style guides, which is really important in big teams with many developers.

ESlint is highly configurable and extensible.

First of all, we have to install ESLint as follows:

npm i eslint

After installing ESlint, we can configure it using an .eslintrc file in the root folder of the project:

https://github.com/MariamKochumian/eslintConfig

We use the ‘rules’ key to add some rules. There are three levels of rules:

  • off or 0: The rule is disabled
  • warn or 1: The rule is a warning.
  • error or 2: The rule throws an error.

After ESlint configuration we can add Git pre-commit hook with Husky and lint-staged.

Clean Up Your React Code (The 2nd Part)

Written By Mariam Kochumian.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by Mariam Kochumian

~ Senior Software Engineer 👩‍💻 ~ JavaScript enthusiast 🙃 ~ Sunshine makes me happy ☀️

Responses (7)

Write a response

Thank you for sharing this.

--

Thank you!

--