Learning React Modern Patterns for Developing React Apps
Total Page:16
File Type:pdf, Size:1020Kb
Second Edition Learning React Modern Patterns for Developing React Apps Alex Banks & Eve Porcello SECOND EDITION Learning React Modern Patterns for Developing React Apps Alex Banks and Eve Porcello Beijing Boston Farnham Sebastopol Tokyo Learning React by Alex Banks and Eve Porcello Copyright © 2020 Alex Banks and Eve Porcello. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Acquisitions Editor: Jennifer Pollock Indexer: Judith McConville Development Editor: Angela Rufino Interior Designer: David Futato Production Editor: Kristen Brown Cover Designer: Karen Montgomery Copyeditor: Holly Bauer Forsyth Illustrator: Rebecca Demarest Proofreader: Abby Wheeler May 2017: First Edition June 2020: Second Edition Revision History for the Second Edition 2020-06-12: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492051725 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning React, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the authors, and do not represent the publisher’s views. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-492-05172-5 [LSI] Table of Contents Preface. ix 1. Welcome to React. 1 A Strong Foundation 2 React’s Past and Future 2 Learning React: Second Edition Changes 3 Working with the Files 4 File Repository 4 React Developer Tools 4 Installing Node.js 5 2. JavaScript for React. 7 Declaring Variables 8 The const Keyword 8 The let Keyword 9 Template Strings 11 Creating Functions 12 Function Declarations 12 Function Expressions 12 Default Parameters 14 Arrow Functions 14 Compiling JavaScript 17 Objects and Arrays 18 Destructuring Objects 18 Destructuring Arrays 20 Object Literal Enhancement 20 iii The Spread Operator 21 Asynchronous JavaScript 23 Simple Promises with Fetch 24 Async/Await 25 Building Promises 26 Classes 27 ES6 Modules 28 CommonJS 30 3. Functional Programming with JavaScript. 31 What It Means to Be Functional 32 Imperative Versus Declarative 33 Functional Concepts 36 Immutability 36 Pure Functions 38 Data Transformations 40 Higher-Order Functions 47 Recursion 48 Composition 51 Putting It All Together 52 4. How React Works. 57 Page Setup 57 React Elements 58 ReactDOM 61 Children 61 React Components 65 React Components: A Historical Tour 69 5. React with JSX. 71 React Elements as JSX 71 JSX Tips 72 Mapping Arrays with JSX 73 Babel 73 Recipes as JSX 75 React Fragments 82 Intro to webpack 84 Creating the Project 85 Loading the Bundle 94 Source Mapping 94 Create React App 95 iv | Table of Contents 6. React State Management. 97 Building a Star Rating Component 98 The useState Hook 99 Refactoring for Advanced Reusability 104 State in Component Trees 106 Sending State Down a Component Tree 106 Sending Interactions Back up a Component Tree 109 Building Forms 113 Using Refs 114 Controlled Components 115 Creating Custom Hooks 117 Adding Colors to State 119 React Context 120 Placing Colors in Context 122 Retrieving Colors with useContext 123 Stateful Context Providers 125 Custom Hooks with Context 126 7. Enhancing Components with Hooks. 129 Introducing useEffect 129 The Dependency Array 132 Deep Checking Dependencies 136 When to useLayoutEffect 141 Rules to Follow with Hooks 143 Improving Code with useReducer 146 useReducer to Handle Complex State 148 Improving Component Performance 150 shouldComponentUpdate and PureComponent 153 When to Refactor 154 8. Incorporating Data. 155 Requesting Data 155 Sending Data with a Request 157 Uploading Files with fetch 157 Authorized Requests 158 Saving Data Locally 159 Handling Promise States 162 Render Props 165 Virtualized Lists 167 Creating a Fetch Hook 172 Table of Contents | v Creating a Fetch Component 174 Handling Multiple Requests 176 Memozing Values 177 Waterfall Requests 181 Throttling the Network Speed 184 Parallel Requests 185 Waiting for Values 187 Canceling Requests 188 Introducing GraphQL 191 GitHub GraphQL API 191 Making a GraphQL Request 193 9. Suspense. 199 Error Boundaries 201 Code Splitting 205 Introducing: The Suspense Component 207 Using Suspense with Data 208 Throwing Promises 212 Building Suspenseful Data Sources 216 Fiber 220 10. React Testing. 223 ESLint 223 ESLint Plug-Ins 227 Prettier 229 Configuring Prettier by Project 229 Prettier in VSCode 230 Typechecking for React Applications 231 PropTypes 231 Flow 235 TypeScript 238 Test-Driven Development 241 TDD and Learning 241 Incorporating Jest 242 Create React App and Testing 242 Testing React Components 246 Queries 249 Testing Events 250 Using Code Coverage 252 vi | Table of Contents 11. React Router. 255 Incorporating the Router 256 Router Properties 259 Nesting Routes 261 Using Redirects 264 Routing Parameters 265 12. React and the Server. 271 Isomorphic Versus Universal 271 Client and Server Domains 272 Server Rendering React 274 Server Rendering with Next.js 280 Gatsby 285 React in the Future 287 Index. 289 Table of Contents | vii Preface This book is for developers who want to learn the React library while learning the latest techniques currently emerging in the JavaScript language. This is an exciting time to be a JavaScript developer. The ecosystem is exploding with new tools, syntax, and best practices that promise to solve many of our development problems. Our aim with this book is to organize these techniques so you can get to work with React right away. We’ll get into state management, React Router, testing, and server rendering, so we promise not to introduce only the basics and then throw you to the wolves. This book does not assume any knowledge of React at all. We’ll introduce all of React’s basics from scratch. Similarly, we won’t assume that you’ve worked with the latest JavaScript syntax. This will be introduced in Chapter 2 as a foundation for the rest of the chapters. You’ll be better prepared for the contents of the book if you’re comfortable with HTML, CSS, and JavaScript. It’s almost always best to be comfortable with these big three before diving into a JavaScript library. Along the way, check out the GitHub repository. All of the examples are there and will allow you to practice hands-on. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. ix Constant width bold Shows commands or other text that should be typed literally by the user. This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/moonhighway/learning-react. If you have a technical question or a problem using the code examples, please send email to [email protected]. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require per‐ mission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Learning React by Alex Banks and Eve Porcello (O’Reilly). Copyright 2020 Alex Banks and Eve Porcello, 978-1-492-05172-5.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at [email protected]. x | Preface O’Reilly Online Learning For more than 40 years, O’Reilly Media has provided technol‐ ogy and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit http://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information.