React Design Patterns and Best Practices
eBook - ePub

React Design Patterns and Best Practices

Design, build and deploy production-ready web applications using standard industry practices, 2nd Edition

  1. 350 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

React Design Patterns and Best Practices

Design, build and deploy production-ready web applications using standard industry practices, 2nd Edition

About this book

Build modular React web apps that are scalable, maintainable and powerful using design patterns and insightful practices

Key Features

  • Get familiar with design patterns in React like Render props and Controlled/uncontrolled inputs
  • Learn about class/ functional, style and high order components with React
  • Work through examples that can be used to create reusable code and extensible designs

Book Description

React is an adaptable JavaScript library for building complex UIs from small, detached bits called components. This book is designed to take you through the most valuable design patterns in React, helping you learn how to apply design patterns and best practices in real-life situations.

You'll get started by understanding the internals of React, in addition to covering Babel 7 and Create React App 2.0, which will help you write clean and maintainable code. To build on your skills, you will focus on concepts such as class components, stateless components, and pure components. You'll learn about new React features, such as the context API and React Hooks that will enable you to build components, which will be reusable across your applications. The book will then provide insights into the techniques of styling React components and optimizing them to make applications faster and more responsive. In the concluding chapters, you'll discover ways to write tests more effectively and learn how to contribute to React and its ecosystem.

By the end of this book, you will be equipped with the skills you need to tackle any developmental setbacks when working with React. You'll be able to make your applications more flexible, efficient, and easy to maintain, thereby giving your workflow a boost when it comes to speed, without reducing quality.

What you will learn

  • Get familiar with the new React features, like context API and React Hooks
  • Learn the techniques of styling and optimizing React components
  • Make components communicate with each other by applying consolidate patterns
  • Use server-side rendering to make applications load faster
  • Write a comprehensive set of tests to create robust and maintainable code
  • Build high-performing applications by optimizing components

Who this book is for

This book is for web developers who want to increase their understanding of React and apply it to real-life application development. Prior experience with React and JavaScript is assumed.

Trusted by 375,005 students

Access to over 1 million titles for a fair monthly price.

Study more efficiently using our study tools.

Section 1: Hello React!

In this section, we will learn about the basics of React and modern JavaScript concepts. We will then move on to understanding concepts including JSX, spread attributes, JavaScript templating, and common patterns and code styles. Finally, we will take a look at the basics of functional programming.
The following chapters will be covered in this section:
  • Chapter 1, Taking Your First Steps with React
  • Chapter 2, Clean Up Your Code

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 developers at Facebook and hundreds of contributors within the JavaScript community. React is one of the most popular libraries for creating user interfaces, and it is well-known to be fast, thanks to its smart way of touching the Document Object Model (DOM). It comes with JSX, a new syntax to write markup in JavaScript, which requires you to change your mind regarding the separation of concerns. It has many cool features, such as server-side rendering, which gives you the power to write universal applications.
To follow this book, you will need to know how to use the terminal to install and run npm packages in your Node.js environment. All the examples are written in modern JavaScript, which you should be able to read and understand.
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 changes 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 the JavaScript fatigue, and what you can do to avoid the most common errors developers make when approaching the React ecosystem

Declarative programming

Reading the React documentation or blog posts about React, you have undoubtedly come across the term declarative. One of the reasons why React is so powerful is because it enforces a declarative programming paradigm.
Consequently, 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 the problem 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.
A real-life parallel in the imperative world would be entering a bar for a beer, and giving the following instructions to the bartender:
  1. Take a glass from the shelf.
  2. Put the glass in front of the draft.
  3. Pull down the handle until the glass is full.
  4. Pass me the glass.
In the declarative world, you would just say: Beer, please.
The declarative approach of asking for a beer assumes that the bartender knows how to serve one, and that is an important aspect of the way declarative programming works.
Let's move into a JavaScript example, writing a simple function that, given an array of uppercase strings, returns an array with the same strings in lowercase:
 toLowerCase(['FOO', 'BAR']) // ['foo', 'bar']
An imperative function to solve the problem would be implemented as follows:
 const toLowerCase = input => { 
const output = [];

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

return output;
};
First of all, an empty array to contain the result gets created. Then, the function loops through all the elements of the input array and pushes the lowercase values into the empty array. Finally, the output array gets returned.
A declarative solution would be as follows:
 const toLowerCase = input => input.map(value => value.toLowerCase());
The items of the input array are passed to a map function that returns a new array containing the lowercase 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: showing a map with a marker.
The JavaScript implementation (using the Google Maps SDK) is as follows:
 const map = new google.maps.Map(document.getElementById('map'), { 
zoom: 4,
center: myLatLng
});

const marker = new google.maps.Marker({
position: myLatLng,
title: 'Hello World!'
});

marker.setMap(map);
It is imperative because all the instructions needed to create the map, and create the marker and attach it to the map, are described inside the code one after the other.
A React component to show a map on a page would look like this instead:
 <Gmaps zoom={4} center={myLatLng}> 
<Marker position={myLatLng} title="Hello world!" />
</Gmaps>
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.

React elements

This book assumes that you are familiar with components and their instances, but there is another object you should know 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 oppositely: 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, that 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 a 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.
The type is important because it tells React how to deal with the element itself. If the type is a string, the element represents a DOM node, while if the type is a function, the element i...

Table of contents

  1. Title Page
  2. About Packt
  3. Copyright and Credits
  4. Contributors
  5. Preface
  6. Section 1: Hello React!
  7. Taking Your First Steps with React
  8. Clean Up Your Code
  9. Section 2: How React works
  10. Creating Truly Reusable Components
  11. Compose All the Things
  12. Proper Data Fetching
  13. Write Code for the Browser
  14. Section 3: Performance, Improvements and Production!
  15. Make Your Components Look Beautiful
  16. Server-Side Rendering for Fun and Profit
  17. Improve the Performance of Your Applications
  18. About Testing and Debugging
  19. React Router
  20. Anti-Patterns to be Avoided
  21. Deploying to Production
  22. Next Steps
  23. Other Books You May Enjoy

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn how to download books offline
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 990+ topics, we’ve got you covered! Learn about our mission
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more about Read Aloud
Yes! You can use the Perlego app on both iOS and Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app
Yes, you can access React Design Patterns and Best Practices by Carlos Santana Roldan in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in JavaScript. We have over one million books available in our catalogue for you to explore.