React 17 Design Patterns and Best Practices - Third Edition

By Carlos Santana Roldán
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Taking Your First Steps with React

About this book

React is an open-source, adaptable JavaScript library for building complex user interfaces (UIs) from small, detached bits called components. This book will help you to use React effectively to make your applications more flexible, easier to maintain, and improve their performance, while giving your workflow a huge boost by improving speed without affecting quality.

You’ll start by understanding the internals of React, before gradually moving on to writing maintainable and clean code. The chapters that follow will show you how to build components that are reusable across the application, structure applications, and create forms that actually work. Later, you will build on your knowledge by exploring how to style React components and optimize them to make applications faster and more responsive. Finally, you’ll write tests effectively and learn how to contribute to React and its ecosystem.

By the end of this book, you'll be able to avoid the process of trial and error and developmental headaches, and instead, have the skills you need to efficiently build and deploy real-world React web applications.

Publication date:
May 2021
Publisher
Packt
Pages
394
ISBN
9781800560444

 
Taking Your First Steps with React

Hello, readers!

This book assumes that you already know what React is and what problems it can solve for you. You may have written a small/medium application with React, and you want to improve your skills and answer all of your open questions. You should know that React is maintained by the developers at Facebook and hundreds of contributors within the JavaScript community. React is one of the most popular libraries for creating UIs, and it is well known to be fast, thanks to its smart way of working with the Document Object Model (DOM). It comes with JSX, a new syntax for writing markup in JavaScript, which requires you to change your thinking regarding the separation of concerns. It has many cool features, such as server-side rendering, which gives you the power to write universal applications.

In this first chapter, we will go through some basic concepts that are essential to master in order to use React effectively, but are straightforward enough for beginners to figure out:

  • The difference between imperative and declarative programming
  • React components and their instances, and how React uses elements to control the UI flow
  • How React changed the way we build web applications, enforcing a different new concept of separation of concerns, and the reasons behind its unpopular design choice
  • Why people feel JavaScript fatigue, and what you can do to avoid the most common errors developers make when approaching the React ecosystem
  • How TypeScript changed the game

 

Technical requirements

In order to follow this book, you need to have some minimal experience using the terminal to run a few Unix commands. Also, you need to install Node.js. You have two options. The first one is to download Node.js directly from the official website, https://nodejs.org, and the second option (recommended) is to install Node Version Manager (NVM) from https://github.com/nvm-sh/nvm.

If you decide to go with NVM, you can install any version of Node.js you want and switch the versions with the nvm install command:

# "node" is an alias for the latest version:
nvm install node

# You can also install a global version of node (will install the latest from that version):
nvm install 10
nvm install 9
nvm install 8
nvm install 7
nvm install 6

# Or you can install a very specific version:
nvm install 6.14.3

After you have installed the different versions, you can switch them by using the nvm use command:

nvm use node # for latest version
nvm use 10
nvm use 6.14.3

Finally, you can specify a default node version by running the following command:

nvm alias default node
nvm alias default 10
nvm alias default 6.14.3

In short, here is a list of the requirements to complete the chapter:

You can find the code for this chapter in the book's GitHub repository: https://github.com/PacktPublishing/React-17-Design-Patterns-and-Best-Practices-Third-Edition.

 

Differentiating between declarative and imperative programming

When reading the React documentation or blog posts about React, you will have undoubtedly come across the term declarative. One of the reasons why React is so powerful is that it enforces a declarative programming paradigm.

Therefore, to master React, it is essential to understand what declarative programming means and what the main differences between imperative and declarative programming are. The easiest way to approach this is to think about imperative programming as a way of describing how things work, and declarative programming as a way of describing what you want to achieve.

Entering a bar for a beer is a real-life example in the imperative world, where normally you will give the following instructions to the bartender:

  1. Find a glass and collect it from the shelf.
  2. Place the glass under the tap.
  3. Pull down the handle until the glass is full.
  4. Hand me the glass.

In the declarative world, you would just say "Can I have a beer, please?"

The declarative approach assumes that the bartender already knows how to serve a beer, an important aspect of the way declarative programming works.

Let's move into a JavaScript example. Here we will write a simple function that, given an array of lowercase strings, returns an array with the same strings in uppercase:

toUpperCase(['foo', 'bar']) // ['FOO', 'BAR']

An imperative function to solve the problem would be implemented as follows:

const toUpperCase = input => { 
const output = []

for (let i = 0; i < input.length; i++) {
output.push(input[i].toUpperCase())
}

return output
}

First of all, an empty array to contain the result is created. Then, the function loops through all the elements of the input array and pushes the uppercase values into the empty array. Finally, the output array is returned.

A declarative solution would be as follows:

const toUpperCase = input => input.map(value => value.toUpperCase())

The items of the input array are passed to a map function that returns a new array containing the uppercase values. There are some significant differences to note: the former example is less elegant and it requires more effort to be understood. The latter is terser and easier to read, which makes a huge difference in big code bases, where maintainability is crucial.

Another aspect worth mentioning is that in the declarative example, there is no need to use variables, nor to keep their values updated during the execution. Declarative programming tends to avoid creating and mutating a state.

As a final example, let's see what it means for React to be declarative. The problem we will try to solve is a common task in web development: creating a toggle button.

Imagine a simple UI component such as a toggle button. When you click it, it turns green (on) if it was previously gray (off), and switches to gray (off) if it was previously green (on).

The imperative way of doing this would be as follows:

const toggleButton = document.querySelector('#toggle')

toogleButton.addEventListener('click', () => {
if (toggleButton.classList.contains('on')) {
toggleButton.classList.remove('on')
toggleButton.classList.add('off')
} else {
toggleButton.classList.remove('off')
toggleButton.classList.add('on')
}
})

It is imperative because of all the instructions needed to change the classes. In contrast, the declarative approach using React would be as follows:

// To turn on the Toggle
<Toggle on />

// To turn off the toggle
<Toggle />

In declarative programming, developers only describe what they want to achieve, and there's no need to list all the steps to make it work. The fact that React offers a declarative approach makes it easy to use, and consequently, the resulting code is simple, which often leads to fewer bugs and more maintainability.

In the next section, you will learn how React elements work and you will get more context on how props are being passed on a React component.

 

How React elements work

This book assumes that you are familiar with components and their instances, but there is another object you should know about if you want to use React effectively – the element.

Whenever you call createClass, extend Component, or declare a stateless function, you are creating a component. React manages all the instances of your components at runtime, and there can be more than one instance of the same component in memory at a given point in time.

As mentioned previously, React follows a declarative paradigm, and there's no need to tell it how to interact with the DOM; you declare what you want to see on the screen, and React does the job for you.

As you might have already experienced, most other UI libraries work the other way round: they leave the responsibility of keeping the interface updated to the developer, who has to manage the creation and destruction of the DOM elements manually.

To control the UI flow, React uses a particular type of object, called an element, which describes what has to be shown on the screen. These immutable objects are much simpler compared to the components and their instances and contain only the information that is strictly needed to represent the interface.

The following is an example of an element:

  { 
type: Title,
props: {
color: 'red',
children: 'Hello, Title!'
}
}

Elements have type, which is the most important attribute, and some properties. There is also a particular property, called children, that is optional and represents the direct descendant of the element.

type is important because it tells React how to deal with the element itself. If type is a string, the element represents a DOM node, while if type is a function, the element is a component.

DOM elements and components can be nested with each other as follows, to represent the render tree:

  { 
type: Title,
props: {
color: 'red',
children: {
type: 'h1',
props: {
children: 'Hello, H1!'
}
}
}
}

When the type of the element is a function, React calls the function, passing props to get back the underlying elements. It keeps on performing the same operation recursively on the result until it gets a tree of DOM nodes that React can render on the screen. This process is called reconciliation, and it is used by both React DOM and React Native to create the UIs of their respective platforms.

React is a game-changer, so at the beginning, the React syntax might seem weird to you, but once you understand how it works, you will love it, and for this, you need to unlearn everything you know so far.

 

Unlearning everything

Using React for the first time usually requires an open mind because it is a new way of designing web and mobile applications. React tries to innovate the way we build UIs following a path that breaks most of the well-known best practices.

In the last two decades, we learned that the separation of concerns is important, and we used to think about it as separating the logic from the templates. Our goal has always been to write the JavaScript and the HTML in different files. Various templating solutions have been created to help developers achieve this.

The problem is that most of the time, that kind of separation is just an illusion and the truth is that the JavaScript and the HTML are tightly coupled, no matter where they live.

Let's see an example of a template:

{{#items}} 
{{#first}}
<li><strong>{{name}}</strong></li>
{{/first}}
{{#link}}
<li><a href="{{url}}">{{name}}</a></li>
{{/link}}
{{/items}}

The preceding snippet is taken from the Mustache website, one of the most popular templating systems.

The first row tells Mustache to loop through a collection of items. Inside the loop, there is some conditional logic to check whether the #first and #link properties exist and, depending on their values, a different piece of HTML is rendered. Variables are wrapped in curly braces.

If your application only has to display some variables, a templating library could represent a good solution, but when it comes to starting to work with complex data structures, things change. Templating systems and their Domain-Specific Language (DSL) offer a subset of features, and they try to provide the functionalities of a real programming language without reaching the same level of completeness. As shown in the example, templates highly depend on the models they receive from the logic layer to display the information.

On the other hand, JavaScript interacts with the DOM elements rendered by the templates to update the UI, even if they are loaded from separate files. The same problem applies to styles – they are defined in a different file, but they are referenced in the templates, and the CSS selectors follow the structure of the markup, so it is almost impossible to change one without breaking the other, which is the definition of coupling. That is why the classic separation of concerns ended up being more the separation of technologies, which is, of course, not a bad thing, but it doesn't solve any real problems.

React tries to move a step forward by putting the templates where they belong – next to the logic. The reason it does that is that React suggests you organize your applications by composing small bricks called components. The framework should not tell you how to separate the concerns because every application has its own, and only the developers should decide how to limit the boundaries of their applications.

The component-based approach drastically changes the way we write web applications, which is why the classic concept of separation of concerns is gradually being taken over by a much more modern structure. The paradigm enforced by React is not new, and it was not invented by its creators, but React has contributed to making the concept mainstream and, most importantly, popularized it in such a way that it is easier to understand for developers with different levels of expertise.

Rendering of a React component looks like this:

return ( 
<button style={{ color: 'red' }} onClick={this.handleClick}>
Click me!
</button>
)

We all agree that it seems a bit weird in the beginning, but that is just because we are not used to that kind of syntax. As soon as we learn it and we realize how powerful it is, we understand its potential. Using JavaScript for both logic and templating not only helps us separate our concerns in a better way, but it also gives us more power and more expressivity, which is what we need to build complex UIs.

That is why even if the idea of mixing JavaScript and HTML sounds weird in the beginning, it is vital to give React 5 minutes. The best way to get started with new technology is to try it on a small side project and see how it goes. In general, the right approach is always to be ready to unlearn everything and change your mindset if the long-term benefits are worth it.

There is another concept that is pretty controversial and hard to accept, and that the engineers behind React are trying to push to the community: moving the styling logic inside the component, too. The end goal is to encapsulate every single technology used to create our components and separate the concerns according to their domain and functionalities.

Here is an example of a style object taken from the React documentation:

const divStyle = { 
color: 'white',
backgroundImage: `url(${imgUrl})`,
WebkitTransition: 'all', // note the capital 'W' here
msTransition: 'all' // 'ms' is the only lowercase vendor prefix
}

ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode)

This set of solutions, where developers use JavaScript to write their styles, is known as #CSSinJS, and we will talk about it extensively in Chapter 8, Making Your Components Look Beautiful.

In the next section, we will see how to avoid JavaScript fatigue, which is caused by the large number of configurations that are needed to run a React application (webpack mainly).

 

Understanding JavaScript fatigue

There is a prevailing opinion that React consists of a vast set of technologies and tools, and if you want to use it, you are forced to deal with package managers, transpilers, module bundlers, and an infinite list of different libraries. This idea is so widespread and shared among people that it has been clearly defined, and has been given the name JavaScript fatigue.

It is not hard to understand the reasons behind this. All the repositories and libraries in the React ecosystem are made using shiny new technologies, the latest version of JavaScript, and the most advanced techniques and paradigms.

Moreover, there is a massive number of React boilerplate on GitHub, each with tens of dependencies to offer solutions for any problems. It is straightforward to think that all these tools are required to start using React, but this is far from the truth. Despite this common way of thinking, React is a pretty tiny library, and it can be used inside any page (or even inside JSFiddle) in the same way everyone used to use jQuery or Backbone, just by including the script on the page before the closing body element.

There are two scripts because React is split into two packages:

  • react: Implements the core features of the library
  • react-dom: Contains all the browser-related features

The reason behind this is that the core package is used to support different targets, such as React DOM in browsers and React Native on mobile devices. Running a React application inside a single HTML page does not require any package manager or complex operation. You can just download the distribution bundle and host it yourself (or use https://unpkg.com/), and you are ready to get started with React and its features in a few minutes.

Here are the URLs to be included in the HTML to start using React:

If we add the core React library only, we cannot use JSX because it is not a standard language supported by the browser; but the whole point is to start with the bare minimum set of features and add more functionalities as soon as they are needed. For a simple UI, we could just use createElement (_jsx on React 17) and only when we start building something more complex can we include a transpiler to enable JSX and convert it into JavaScript. As soon as the app grows a bit more, we may need a router to handle different pages and views, and we can include that as well.

At some point, we may want to load data from some API endpoints, and if the application keeps growing, we will reach the point where we need some external dependencies to abstract complex operations. Only at that very moment should we introduce a package manager. Then, the time will come to split our application into separate modules and organize our files in the right way. At that point, we should start thinking about using a module bundler.

Following this simple approach, there's no fatigue. Starting with a boilerplate that has 100 dependencies and tens of npm packages of which we know nothing is the best way to get lost. It is important to note that every programming-related job (and frontend engineering in particular) requires continuous learning. It is the nature of the web to evolve at a breakneck pace and change according to the needs of both users and developers. This is the way our environment has worked since the beginning and is what makes it very exciting.

As we gain experience working on the web, we learn that we cannot master everything and we should find the right way to keep ourselves updated to avoid fatigue. We are able to follow all the new trends without jumping into the new libraries for the sake of it unless we have time for a side project.

It is astonishing how, in the JavaScript world, as soon as a specification is announced or drafted, someone in the community implements it as a transpiler plugin or a polyfill, letting everyone else play with it while the browser vendors agree and start supporting it.

This is something that makes JavaScript and the browser a completely different environment compared to any other language or platform. The downside of it is that things change quickly, but it is just a matter of finding the right balance between betting on new technologies versus staying safe.

In any case, Facebook developers care a lot about the Developer Experience (DX), and they listen carefully to the community. So, even if it is not true that to use React we are required to learn hundreds of different tools, they realized that people were feeling the fatigue and they released a CLI tool that makes it incredibly easy to scaffold and run a real React application.

The only requirement is to use a node.js/npm environment and install the CLI tool globally as follows:

npm install -g create-react-app

When the executable is installed, we can use it to create our application, passing a folder name:

create-react-app hello-world --template typescript

Finally, we move into the folder of our application with cd hello-world, and we just run the following command:

npm start

Magically, our application is running with a single dependency, but with all the features needed to build a complete React application using the most advanced techniques. The following screenshot shows the default page of an application created with create-react-app:

This is basically your first React application.

 

Introducing TypeScript

TypeScript is a typed superset of JavaScript that is compiled to JavaScript, which means TypeScript is JavaScript with some additional features. TypeScript was designed by Anders Hejlsberg (the designer of C#) at Microsoft and is open source.

Let's see what the features of TypeScript are and how to convert JavaScript to TypeScript.

TypeScript features

This section will try to summarize the most important features you should be taking advantage of:

  • TypeScript is JavaScript: Any JavaScript code you write will work with TypeScript, which means if you already know how to use JavaScript basically you have all you need to do TypeScript; you just need to learn how to add types to your code. All the TypeScript code is transformed into JavaScript at the end.
  • JavaScript is TypeScript: This just means that you can rename any valid .js file with the .ts extension, and it will work.
  • Error checking: TypeScript compiles the code and checks for errors, which helps a lot to highlight errors before we run our code.
  • Strong typing: By default, JavaScript is not strongly typed. With TypeScript, you can add types to all your variables and functions, and you can even specify the returned value types.
  • Object-oriented programming supported: It supports concepts such as classes, interfaces, inheritance, and so on.

Converting JavaScript code into TypeScript

In this section, we will see how to transform some JavaScript code into TypeScript.

Let's suppose we have to check whether a word is a palindrome. The JavaScript code for this algorithm will be as follows:

function isPalindrome(word) {
const lowerCaseWord = word.toLowerCase()
const reversedWord = lowerCaseWord.split('').reverse().join('')

return lowerCaseWord === reversedWord
}

You can name this file palindrome.ts.

As you can see, we are receiving a string variable (word), and we are returning a boolean value, so how will this be translated to TypeScript?

function isPalindrome(word: string): boolean {
const lowerCaseWord = word.toLowerCase()
const reversedWord = lowerCaseWord.split('').reverse().join('')

return lowerCaseWord === reversedWord
}

You're probably thinking great, I just specified the string type as word and boolean type to the function returned value, but now what?

If you try to run the function with some value that is different from a string, you will get a TypeScript error:

console.log(isPalindrome('Level')) // true
console.log(isPalindrome('Anna')) // true
console.log(isPalindrome('Carlos')) // false
console.log(isPalindrome(101)) // TS Error
console.log(isPalindrome(true)) // TS Error
console.log(isPalindrome(false)) // TS Error

So, if you try to pass a number to the function, you will get the following error:

That's why TypeScript is very useful because it will force you to be more strict and explicit with your code.

Types

In the last example, we saw how to specify some primitive types for our function parameter and returned value, but you're probably wondering how you can describe an object or array with more details. Types can help us to describe our objects or arrays in a better way. For example, let's suppose you want to describe a User type to save the information into the database:

type User = {
username: string
email: string
name: string
age: number
website: string
active: boolean
}

const user: User = {
username: 'czantany',
email: '[email protected]',
name: 'Carlos Santana',
age: 33,
website: 'http://www.js.education',
active: true
}

// Let's suppose you will insert this data using Sequelize...
models.User.create({ ...user }}

We get the following error if you forget to add one of the nodes or put an invalid value in one of them:

If you need optional nodes, you can always put a ? next to the name of the node, as shown in the following code block:

type User = {
username: string
email: string
name: string
age?: number
website: string
active: boolean
}
You can name type as you want, but a good practice to follow is to add a prefix of T, so, for example, the User type will become TUser. In this way, you can quickly recognize that it is type and you don't get confused thinking it is a class or a React component.

Interfaces

Interfaces are very similar to types and sometimes developers don't know the differences between them. Interfaces can be used to describe the shape of an object or function signature just like types, but the syntax is different:

interface User {
username: string
email: string
name: string
age?: number
website: string
active: boolean
}
You can name an interface as you want, but a good practice to follow is to add a prefix of I, so, for example, the User interface will become IUser. In this way, you can quickly recognize that it is an interface and you don't get confused thinking it is a class or a React component.

An interface can also be extended, implemented, and merged.

Extending

An interface or type can also be extended, but again the syntax will differ, as shown in the following code block:

// Extending an interface
interface IWork {
company: string
position: string
}

interface IPerson extends IWork {
name: string
age: number
}

// Extending a type
type TWork = {
company: string
position: string
}

type TPerson = TWork & {
name: string
age: number
}

// Extending an interface into a type
interface
IWork {
company: string
position: string
}

type TPerson = IWork & {
name: string
age: number
}

As you can see, by using the & character, you can extend a type, while you extend an interface using the extends keyword.

Implementing

A class can implement an interface or type alias in the same exact way. But it cannot implement (or extend) a type alias that names a union type, for example:

// Implementing an interface
interface IWork {
company: string
position: string
}

class Person implements IWork {
name: 'Carlos'
age: 33
}

// Implementing a type
type TWork = {
company: string
position: string
}

class Person2 implements TWork {
name: 'Cristina'
age: 32
}

// You can't implement a union type
type TWork2 =
{ company: string; position: string } | { name: string; age: number }

class
Person3 implements TWork2 {
company: 'Google'
position: 'Senior Software Engineer'
}

If you write that code, you will get the following error in your editor:

As you can see, you are not able to implement a union type.

Declaration merging

Unlike a type, an interface can be defined multiple times and will be treated as a single interface (all declarations will be merged), as shown in the following code block:

interface IUser {
username: string
email: string
name: string
age?: number
website: string
active: boolean
}

interface IUser {
country: string
}

const user: IUser = {
username: 'czantany',
email: '[email protected]',
name: 'Carlos Santana',
country: 'Mexico',
age: 33,
website: 'http://www.js.education',
active: true
}

This is very useful when you need to extend your interfaces in different scenarios by just re-defining the same interface.

 

Summary

In this first chapter, we have learned some basic concepts that are very important for following the rest of the book, and that are crucial to working with React daily. We now know how to write declarative code, and we have a clear understanding of the difference between the components we create and the elements that React uses to display their instances on the screen.

We learned the reasons behind the choice of locating logic and templates together, and why that unpopular decision has been a big win for React. We went through the reasons why it is common to feel fatigued in the JavaScript ecosystem, but we have also seen how to avoid those problems by following an iterative approach.

We learned how to use TypeScript to create some basic types and interfaces. Finally, we have seen what the new create-react-app CLI is, and we are now ready to start writing some real code.

In the next chapter, you will learn how to use JSX/TSX code and apply very useful configurations to improve your code style.

About the Author

  • Carlos Santana Roldán

    Carlos Santana Roldán is a senior web developer with more than 13 years of experience. Currently, he is working as a senior software engineer at Snapchat. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.

    Browse publications by this author
Book Title
Unlock this book and the full library for FREE
Start free trial