React Anti-Patterns - Juntao Qiu - E-Book

React Anti-Patterns E-Book

Juntao Qiu

0,0
24,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Take your React development skills to the next level by examining common anti-patterns with expert insights and practical solutions, to refine your codebases into sophisticated and scalable creations. Through this easy-to-follow guide, React Anti-Patterns serves as a roadmap to elevating the efficiency and maintainability of your React projects.
You’ll begin by familiarizing yourself with the essential aspects of React before exploring strategies for structuring React applications and creating well-organized, modular, and easy-to-maintain codebases. From identifying and addressing common anti-patterns using refactoring techniques to harnessing the power of test-driven development (TDD), you’ll learn about the tools and techniques necessary to create reliable and robust tests. As you advance, you’ll get to grips with business logic and design patterns that offer solutions to prevalent challenges faced in React development. The book also offers insights into using composition patterns, such as code splitting and multiple entry points, to enhance the flexibility and modularity of your React applications, guiding you through end-to-end project implementation.
By the end of this React book, you’ll be able to overcome common challenges and pitfalls to transform your React projects into elegant, efficient, and maintainable codebases.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 353

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



React Anti-Patterns

Build efficient and maintainable React applications with test-driven development and refactoring

Juntao Qiu

BIRMINGHAM—MUMBAI

React Anti-Patterns

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Jane D’Souza

Senior Editor: Hayden Edwards

Technical Editor: K Bimala Singha

Copy Editor: Safis Editing

Project Coordinator: Aishwarya Mohan

Proofreader: Safis Editing

Indexer: Subalakshmi Govindhan

Production Designer: Shankar Kalbhor

Marketing Coordinators: Namita Velgekar and Nivedita Pandey

First published: January 2024

Production reference: 1071223

Published by

Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-80512-397-2

www.packtpub.com

To my loving wife, Mansi, and joyful daughter, Luna – your laughter was my daily respite, and your support allowed me the time at my desk to bring this book to fruition. While the pages reflect my work, they also echo your sacrifice and love. Thank you.

– Juntao

Contributors

About the author

Juntao Qiu is an accomplished software developer with over 15 years of industry experience, dedicated to helping others write better code. With a strong passion for crafting maintainable and high-quality code, he has become a trusted resource in the industry. As an author, Juntao has shared his expertise through influential books such as Maintainable React (2022) and Test-Driven Development with React and TypeScript – Second Edition (2023).

He orchestrates a blend of code snippets, illustrations, and before and after comparisons to unravel intricate concepts, making them accessible to fellow developers. His insightful blog posts at https://juntao.substack.com/ and educational videos on YouTube www.youtube.com/@icodeit.juntao) are a testament to his commitment to sharing knowledge and fostering a deeper understanding of coding practices within the developer community.

I am immensely thankful to my Atlassian teammates, Alex Reardon, Daniel Del Core, Michael Dougall, and many others. Many of the design patterns elucidated in this book germinated from our collective intellect while engrossed in Atlassian Design System components. A special shoutout to Tom Gasson, with whom I had an enriching time developing an internal system; our dialogues, particularly on React Context, have been significantly enlightening.

I also extend my appreciation to James Sinclair and Jason Sheehy for our enlightening discussions on TDD within our current monorepo. A special thank you goes to Vanessa Goah and Mirela Tomicic, who were instrumental during my recent onboarding. Their willingness to engage with my inquiries and provide clarity amid the myriad documents and conventions significantly accelerated my adaptation to the new project and enriched my understanding of the patterns embedded within the code base – a treasure trove of ideas discussed in this book.

My heartfelt appreciation goes to my former colleagues at Thoughtworks. Martin Fowler, your guidance has been a beacon, refining my focus and teaching me the essence of audience-centric writing. I am grateful to Xiaojun Ren for the stimulating design discussions, which were often accompanied by our serene strolls through the chilly suburbs of Melbourne. Thanks to Andy Marks and Cam Jackson for their meticulous reviews and insightful suggestions on technical nuances and linguistic improvements. The consultancy nature of the work at Thoughtworks provided a fertile ground to cross-pollinate ideas with various teams and individuals, an experience I hold dear.

A big thank you to my editor, Hayden Edwards, whose professional editing suggestions were instrumental in enhancing the narrative flow of this book. The journey from a manuscript to a published book is indeed a collaborative venture, and the unseen yet pivotal contributions from the team behind the scenes have been invaluable. Your expertise and dedication have breathed life into this work, and for that, I am profoundly grateful.

About the reviewers

Dennis Persson is a Swedish full stack web and mobile developer with over 10 years of expertise and a master of science degree in computer science and engineering. His academic journey includes a noteworthy tenure at Linköping University, where he imparted knowledge in more than a dozen courses, including both theoretical and practical applications of cutting-edge technologies.

Parallel to his current role as an application developer, Dennis manages a tech blog, providing insights into the evolving tech landscape. This unique combination of academic depth, practical expertise, and knowledge-sharing positions Dennis as a driving force at the intersection of education and industry innovation.

Krishnan Raghavan is an IT professional with over 20 years of experience in the areas of software development and delivery excellence across multiple domains and technologies, ranging from C++, Java, and Python to Angular, Golang, and data warehousing.

When not working, Krishnan likes to spend time with his wife and daughter, reading fiction and nonfiction as well as technical books, and participating in hackathons. Krishnan tries to give back to the community by being part of the GDG Pune volunteer group, helping the team to organize events.

Table of Contents

Preface

Part 1: Introducing the Fundamentals

1

Introducing React Anti-Patterns

Technical requirements

Understanding the difficulty of building UIs

Understanding the state management

Exploring “unhappy paths”

Errors thrown from other components

Learning the unexpected user behavior

Exploring common anti-patterns in React

Props drilling

In-component data transformation

Complicated logic in views

Lack of tests

Duplicated code

Long component with too much responsibility

Unveiling our approach to demolishing anti-patterns

Summary

2

Understanding React Essentials

Technical requirements

Understanding static components in React

Creating components with props

Breaking down UIs into components

Managing internal state in React

Understanding the rendering process

Exploring common React Hooks

useState

useEffect

useCallback

The React Context API

Summary

3

Organizing Your React Application

Technical requirements

Understanding the problem of a less-structured project

Understanding the complications of frontend applications

Exploring common structures in React applications

Feature-based structure

Component-based structure

Atomic design structure

The MVVM structure

Keeping your project structure organized

Implementing the initial structure

Adding an extra layer to remove duplicates

Naming files

Exploring a more customized structure

Summary

4

Designing Your React Components

Technical requirements

Exploring the single responsibility principle

Don’t repeat yourself

Using composition

Combining component design principles

Summary

Part 2: Embracing Testing Techniques

5

Testing in React

Technical requirements

Understanding why we need tests

Learning about different types of tests

Testing individual units with Jest

Writing your first test

Grouping tests

Testing React components

Learning about integration tests

Learning about E2E tests using Cypress

Installing Cypress

Running our first E2E test

Intercepting the network request

Summary

6

Exploring Common Refactoring Techniques

Technical requirements

Understanding refactoring

The common mistakes of refactoring

Adding tests before refactoring

Using Rename Variable

Using Extract Variable

Using Replace Loop with Pipeline

Using Extract Function

Using Introduce Parameter Object

Using Decompose Conditional

Using Move Function

Summary

7

Introducing Test-Driven Development with React

Technical requirements

Understanding TDD

Different styles of TDD

Focusing on user value

Introducing tasking

Introducing the online pizza store application

Breaking down the application requirements

Implementing the application headline

Implementing the menu list

Creating the shopping cart

Adding items to the shopping cart

Refactoring the code

Summary

Part 3: Unveiling Business Logic and Design Patterns

8

Exploring Data Management in React

Technical requirements

Understanding business logic leaks

Introducing the ACL

Introducing a typical usage

Using the fallback or default value

Exploring the prop drilling issue

Using the Context API to resolve prop drilling

Summary

9

Applying Design Principles in React

Technical requirements

Revisiting the Single Responsibility Principle

Exploring the render props pattern

Using composition to apply the SRP

Embracing the Dependency Inversion Principle

Understanding how the DIP works

Applying the DIP in an analytics button

Understanding Command and Query Responsibility Segregation in React

Introducing useReducer

Using a reducer function in a context

Summary

10

Diving Deep into Composition Patterns

Technical requirements

Understanding composition through higher-order components

Reviewing higher-order functions

Introducing HOCs

Implementing an ExpandablePanel component

Exploring React Hooks

Unveiling remote data fetching

Refactoring for elegance and reusability

Developing a drop-down list component

Implementing keyboard navigation

Maintaining simplicity in the Dropdown component

Introducing the Headless Component pattern

The advantages and drawbacks of Headless Component pattern

Libraries and further learnings

Summary

Part 4: Engaging in Practical Implementation

11

Introducing Layered Architecture in React

Technical requirements

Understanding the evolution of a React application

Single-component applications

Multiple-component applications

State management with Hooks

Extracting business models

Layered frontend application

Enhancing the Code Oven application

Refactoring the MenuList through a custom Hook

Transitioning to a class-based model

Implementing the ShoppingCart component

Applying discounts to Items

Exploring the Strategy pattern

Delving into layered architecture

The layered structure of the application

Advantages of layered architecture

Summary

12

Implementing an End-To-End Project

Technical requirements

Getting the OpenWeatherMap API key

Preparing the project’s code base

Reviewing the requirements for the weather application

Crafting our initial acceptance test

Implementing a City Search feature

Introducing the OpenWeatherMap API

Stubbing the search results

Enhancing the search result list

Implementing an ACL

Implementing an Add to Favorite feature

Modeling the weather

Refactoring the current implementation

Enabling multiple cities in the favorite list

Refactoring the weather list

Fetching previous weather data when the application relaunches

Summary

13

Recapping Anti-Pattern Principles

Revisiting common anti-patterns

Props drilling

Long props list/big component

Business leakage

Complicated logic in views

Lack of tests (at each level)

Code duplications

Skimming through design patterns

Higher-order components

Render props

Headless components

Data modeling

Layered architecture

Context as an interface

Revisiting foundational design principles

Single Responsibility Principle

Dependency Inversion Principle

Don't Repeat Yourself

Anti-Corruption Layers

Using composition

Recapping techniques and practices

Writing user acceptance tests

Test-Driven Development

Refactoring and common code smells

Additional resources

Summary

Index

Other Book You May Enjoy

Preface

Building frontend applications is challenging, especially when constructing large ones, and the difficulty escalates without proper guidance. Unfortunately, many React-based applications fall into this scenario due to the library’s UI-centric nature, leaving developers to navigate the other complexities of frontend development on their own. There are numerous other considerations such as asynchronous network requests, accessibility, performance, and state management, to name a few. These factors contribute to the complexity of frontend applications. As the scale of the application grows, maintaining the code becomes an arduous task. Adding new features requires considerably more time than it first appears, and identifying defects (and then fixing them) is equally challenging, if not more so.

However, these challenges are surmountable. We can learn to identify common anti-patterns that cause problems, then employ established patterns, design principles, and practices to address and rectify these issues. History teaches us that solutions derived in one field often find relevance in others, especially when it comes to fundamental design principles such as the Single Responsibility Principle, the Dependency Inversion Principle, and Don’t Repeat Yourself. These principles guided the construction of UNIX systems back in the 1970s and Java Swing applications in the 1990s, and they remain valid today. They will undoubtedly continue to be pertinent for future frameworks and libraries.

This book seeks to delve into these problems and examine how established patterns and practices can mitigate the challenges of building large applications. We’ll see how design principles and design patterns can simplify the design, making the code easier to understand, modify, and maintain in the long run. Through this exploration, readers will gain a deeper understanding of how to navigate the multifaceted world of frontend development with React, ensuring their applications are both robust and maintainable.

Who this book is for

This book is for React developers who are interested in improving the maintainability and efficiency of their code. Whether you’re just starting out or have some experience under your belt, there’s something here for you. It’s beneficial to have a basic understanding of React, but the book aims to guide you through the concepts in a straightforward manner.

The focus is on identifying common anti-patterns and addressing them with established design principles and patterns. Through practical examples and a step-by-step approach, you’ll learn how to simplify your code for better understanding, easier modifications, and long-term maintenance.

What this book covers

In Chapter 1, Introducing React Anti-Patterns, you’ll get a closer look at the hurdles of building user interfaces, handling state management, addressing “unhappy paths,” and identifying common anti-patterns in React.

In Chapter 2, Understanding React Essentials, you will delve into the basics of React covering static components, props, UI breakdown, state management, the rendering process, and common React Hooks to lay a solid foundation for subsequent chapters.

In Chapter 3, Organizing Your React Application, you will learn about different types of project structures in React, exploring their advantages, drawbacks, and practical applications.

In Chapter 4, Designing your React Components, you will learn to identify common anti-patterns in React component design and explore fundamental design principles including the Single Responsibility Principle and Don’t Repeat Yourself to improve component structure.

In Chapter 5, Testing in React, you will learn about the significance of software testing, explore various types of tests such as unit, integration, and end-to-end testing, and get acquainted with popular testing tools including Cypress and Jest, setting a strong foundation for complex testing scenarios in React applications.

In Chapter 6, Exploring Common Refactoring Techniques, you will learn about the essence of refactoring and delve into various refactoring techniques, such as Rename Variable, Extract Variable, and Replace Loop with Pipeline, to enhance code maintainability and readability.

In Chapter 7, Introducing Test-Driven Development with React, you’ll learn the core principles of test-driven development through a practical example, while building various features of a pizza store’s menu page in a React application.

In Chapter 8, Exploring Data Management in React, you’ll delve into the common challenges of state management in React, such as business logic leaks and prop drilling, and explore solutions including employing an Anti-Corruption Layer and utilizing the React context API to enhance code maintainability and user experience.

In Chapter 9, Applying Design Principles in React, you’ll revisit the Single Responsibility Principle, embrace the Dependency Inversion Principle, and understand the application of Command and Query Responsibility Segregation in React to fortify your knowledge of key design principles to aid you in mastering React.

In Chapter 10, Diving Deep into Composition Patterns, you’ll delve into composition through higher-order components and custom Hooks, and explore the headless component pattern. You’ll gain an appreciation of composition techniques for creating scalable, maintainable, and user-friendly UIs in React.

In Chapter 11, Introducing Layered Architecture in React, you’ll explore Layered Architecture, delve into Application Concern Layers, define data models, and learn strategy patterns through a practical example, understanding their significance for large-scale applications.

In Chapter 12, Implementing an End-To-End Project, you’ll traverse the complete process of developing a weather application, from understanding requirements to implementing features such as City Search and Add To Favourite, while ensuring the code remains maintainable, understandable, and extensible.

In Chapter 13, Recapping Anti-Pattern Principles, we’ll take a concise look back at common anti-patterns, React design patterns, and fundamental principles, and recap the techniques and practices discussed earlier in the book, providing a succinct refresher before you continue applying these insights to your own projects.

To get the most out of this book

To delve deeply into this book, having a text editor at hand is crucial; choices such as Visual Studio Code or Vim are commendable, but any other editor of your preference will serve well. An alternative is a full-featured Integrated Development Environment (IDE) such as WebStorm or IntelliJ, which, while not mandatory, could significantly ramp up your efficiency.

A command-line interface is another requisite; for Mac or Linux users, the setup is already in place, but Windows users might need to make an installation—Windows Terminal is a good choice, providing a modern terminal and command-line experience. Preparing these tools in advance will ensure a seamless journey as you traverse through the content of this book.

Software/hardware covered in the book

Operating system requirements

React 16+

Windows, macOS, or Linux

TypeScript 4.9.5

Visual Studio Code or WebStorm

Terminal/Window Terminal (for Windows users)

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/React-Anti-Patterns/. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “We can then pass the desired heading and summary to the Article component.”

A block of code is set as follows:

<Article   heading="Think in components"   summary="It's important to change your mindset when coding with React." />

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<article>   <h3>Think in components</h3>   <p>It's important to change your mindset when coding with React.</p></article>

Any command-line input or output is written as follows:

$ mkdir css $ cd css

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Select System info from the Administration panel.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read React Anti-Patterns, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781805123972

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1:Introducing the Fundamentals

In the first part of this book, you will set foot into the realm of React by exploring its core essentials and understanding how to efficiently structure your application. This part will aid in building a strong foundation, crucial to navigate through the more complex aspects of React that are discussed in the following parts.

This part contains the following chapters:

Chapter 1

,

Introducing React Anti-Patterns

Chapter 2

,

Understanding React Essentials

Chapter 3

,

Organizing Your React Application

Chapter 4

,

Designing Your React Components