Reader small image

You're reading from  React 18 Design Patterns and Best Practices - Fourth Edition

Product typeBook
Published inJul 2023
Reading LevelExpert
PublisherPackt
ISBN-139781803233109
Edition4th Edition
Languages
Tools
Right arrow
Author (1)
Carlos Santana Roldán
Carlos Santana Roldán
author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán

Right arrow

Anti-Patterns to Be Avoided

In this book, you’ve learned how to apply best practices when writing a React application. In the first few chapters, we revisited the basic concepts to build a solid understanding, and then we took a leap into more advanced techniques in the following chapters.

You should now be able to build reusable components, make components communicate with each other, and optimize an application tree to get the best performance. However, developers make mistakes, and this chapter is all about the common anti-patterns we should avoid when using React.

Looking at common errors will help you to avoid them and will aid your understanding of how React works and how to build applications in the React way. For each problem, we will see an example that shows how to reproduce and solve it.

In this chapter, we will cover the following topics:

  • Initializing the state using properties
  • Using indexes as a key
  • Spreading properties on DOM...

Technical requirements

To complete this chapter, you will need the following:

  • Node.js 19+
  • Visual Studio Code

You can find the code for this chapter in the book’s GitHub repository: https://github.com/PacktPublishing/React-18-Design-Patterns-and-Best-Practices-Fourth-Edition/tree/main/Chapter07.

Initializing the state using properties

In this section, we will see how initializing the state using properties received from the parent is usually an anti-pattern. I have used the word usually because, as we will see, once we have it clear in our mind what the problems with this approach are, we might still decide to use it.

One of the best ways to learn something is by looking at the code, so we will start by creating a simple component with a + button to increment a counter.

Let’s create a functional component named Counter, as shown in the following code snippet:

import { FC, useState } from 'react'
type Props = {
  count: number
}
const Counter: FC<Props> = (props) => {}
export default Counter

Now, let’s set our count state:

const [state, setState] = useState<number>(props.count)

The implementation of the click handler is straightforward – we just add 1 to the current count value and store the resulting...

Using indexes as a key

In Chapter 15, Improving the Performance of Your Applications, which talks about performance and the reconciler, we saw how we can help React figure out the shortest path to update the DOM by using the key prop.

The key property uniquely identifies an element in the DOM and React uses it to check whether the element is new or whether it must be updated when the component properties or state change.

Using keys is always a good idea and if you don’t do it, React gives a warning in the console (in development mode). However, it is not simply a matter of using a key; sometimes, the value that we decide to use as a key can make a difference. In fact, using the wrong key can give us unexpected behaviors in some instances. In this section, we will see one of those instances.

Let’s again create a List component, as shown here:

import { FC, useState } from 'react'
const List: FC = () => {
}
export default List

Then we define...

Spreading properties on DOM elements

There is a common practice that has recently been described as an anti-pattern by Dan Abramov; it also triggers a warning in the console when you do it in your React application.

It is a technique that is widely used in the community, and I have personally seen it multiple times in real-world projects. We usually spread the properties to the elements to avoid writing every single one manually, which is shown as follows:

<Component {...props} />

This works very well, and it gets transpiled into the following code by Babel:

_jsx(Component, props)

However, when we spread properties into a DOM element, we run the risk of adding unknown HTML attributes, which is bad practice.

The problem is not related only to the Spread operator; passing non-standard properties one by one leads to the same issues and warnings. Since the Spread operator hides the single properties we are spreading, it is even harder to figure out what...

Summary

Knowing all the best practices is always a good thing, but sometimes, being aware of anti-patterns helps us avoid taking the wrong path. Most importantly, learning the reasons why some techniques are considered bad practice helps us understand how React works, and how we can use it effectively.

In this chapter, we covered four different ways of using components that can harm the performance and behavior of our web applications.

For each one of those, we used an example to reproduce the problem and supplied the changes to apply in order to fix the issue.

We learned why using properties to initialize the state can result in inconsistencies between the state and the properties. We also saw how using the wrong key attribute can produce bad effects on the reconciliation algorithm. Finally, we learned why spreading non-standard properties to DOM elements is considered an anti-pattern.

In the next chapter, we will look into the new React Hooks.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React 18 Design Patterns and Best Practices - Fourth Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781803233109
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán