Table of Contents 3 Book Revision 21 Updated January 13th, 2020 21 Join our Official Community Discord 21 Bug Reports 21 Be notified of updates via Twitter 21 We'd love to hear from you! 21 Foreword 22 How to Get the Most Out of This Book 24 Overview 24 Running Code Examples 25 Project setups 26 Code Blocks and Context 26 Code Block Numbering 27 Getting Help 28 Emailing Us 28 Get excited 29 Part I 30 Your first React Web Application 31 Building Product Hunt 31 Setting up your development environment 32 Code editor 32 Node.js and npm 33 Install Git 33 Browser 33 Special instruction for Windows users 34 Ensure IIS is installed 34 JavaScript ES6/ES7 34 Getting started 35 Sample Code 35 Previewing the application 35 Prepare the app 38 What's a component? 42 Our first component 43 JSX 45 The developer console 47 Babel 49 ReactDOM.render() 51 Building Product 53 Making Product data-driven 56 The data model 56 Using props 57 Rendering multiple products 62 React the vote (your app's first interaction) 67 Propagating the event 68 Binding custom component methods 71 Using state 75 Setting state with this.setState() 77 Updating state and immutability 79 Refactoring with the Babel plugin transform-class-properties 86 Babel plugins and presets 86 Property initializers 88 Refactoring Product 88 Refactoring ProductList 90 Congratulations! 92 Components 93 A time-logging app 93 Getting started 94 Previewing the app 94 Prepare the app 95 Breaking the app into components 100 The steps for building React apps from scratch 108 Step 2: Build a static version of the app 110 TimersDashboard 110 EditableTimer 112 TimerForm 113 ToggleableTimerForm 115 Timer 115 Render the app 117 Try it out 118 Step 3: Determine what should be stateful 119 State criteria 119 Applying the criteria 120 Step 4: Determine in which component each piece of state should live 121 The list of timers and properties of each timer 122 Whether or not the edit form of a timer is open 122 Visibility of the create form 123 Step 5: Hard-code initial states 123 Adding state to TimersDashboard 123 Receiving props in EditableTimerList 125 Props vs. state 126 Adding state to EditableTimer 127 Timer remains stateless 128 Adding state to ToggleableTimerForm 128 Adding state to TimerForm 130 Step 6: Add inverse data flow 134 TimerForm 134 ToggleableTimerForm 136 TimersDashboard 138 Updating timers 140 Adding editability to Timer 141 Updating EditableTimer 141 Updating EditableTimerList 143 Defining onEditFormSubmit() in TimersDashboard 144 Deleting timers 147 Adding the event handler to Timer 147 Routing through EditableTimer 148 Routing through EditableTimerList 149 Implementing the delete function in TimersDashboard 150 Adding timing functionality 151 Adding a forceUpdate() interval to Timer 152 Try it out 154 Add start and stop functionality 154 Add timer action events to Timer 154 Create TimerActionButton 156 Run the events through EditableTimer and EditableTimerList 157 Try it out 160 Methodology review 161 Components & Servers 163 Introduction 163 Preparation 163 server.js 164 The Server API 164 text/html endpoint 166 JSON endpoints 166 Playing with the API 167 Loading state from the server 171 Try it out 174 client 175 Fetch 175 Sending starts and stops to the server 179 Sending creates, updates, and deletes to the server 182 Give it a spin 184 Next up 184 JSX and the Virtual DOM 185 React Uses a Virtual DOM 185 Why Not Modify the Actual DOM? 185 What is a Virtual DOM? 186 Virtual DOM Pieces 186 ReactElement 187 Experimenting with ReactElement 188 Rendering Our ReactElement 190 Adding Text (with children) 192 ReactDOM.render() 193 JSX 194 JSX Creates Elements 194 JSX Attribute Expressions 196 JSX Conditional Child Expressions 197 JSX Boolean Attributes 197 JSX Comments 198 JSX Spread Syntax 198 JSX Gotchas 199 JSX Summary 203 References 204 Advanced Component Configuration with props, state, and children 205 Intro 205 How to use this chapter 206 Components 207 Creating Components - ES6 Classes or Functional Components 207 render() Returns a ReactElement Tree 208 Getting Data into render() 209 props are the parameters 210 PropTypes 211 Default props with getDefaultProps() 213 Context 213 Default value 217 Multiple contexts 218 state 219 Using state: Building a Custom Radio Button 219 Stateful components 225 State updates that depend on the current state 228 Thinking About State 229 Stateless Components 231 Switching to Stateless 232 Stateless Encourages Reuse 235 Talking to Children Components with props.children 235 React.Children.map() & React.Children.forEach() 238 React.Children.toArray() 239 Summary 240 References 241 Forms 242 Forms 101 242 Preparation 243 The Basic Button 244 Events and Event Handlers 246 Back to the Button 247 Text Input 249 Accessing User Input With refs 250 Using User Input 252 Uncontrolled vs. Controlled Components 256 Accessing User Input With state 257 Multiple Fields 260 On Validation 265 Adding Validation to Our App 266 Creating the Field Component 271 Using our new Field Component 275 Remote Data 281 Building the Custom Component 283 Adding CourseSelect 289 Separation of View and State 293 Async Persistence 293 Redux 302 Form Component 309 Connect the Store 314 Form Modules 316 formsy-react 316 react-input-enhancements 317 tcomb-form 317 winterfell 317 react-redux-form 318 Using Webpack with Create React App 319 JavaScript modules 320 Create React App 322 Exploring Create React App 323 public/index.html 324 package.json 325 src/ 328 index.js 331 Booting the app 332 Webpack basics 334 Making modifications to the sample app 341 Hot reloading 341 Auto-reloading 343 Creating a production build 344 Ejecting 348 Buckle up 349 Using Create React App with an API server 351 The completed app 351 How the app is organized 356 The server 357 Client 359 Concurrently 359 Using the Webpack development proxy 364 Webpack at large 366 When to use Webpack/Create React App 366 Unit Testing 368 Writing tests without a framework 368 Preparing Modash 369 Writing the first spec 373 The assertEqual() function 375 What is Jest? 380 Using Jest 381 expect() 381 The first Jest test for Modash 384 The other truncate() spec 386 The rest of the specs 387 Testing strategies for React applications 389 Integration vs Unit Testing 389 Shallow rendering 390 Enzyme 391 Testing a basic React component with Enzyme 392 Setup 392 The App component 393 The first spec for App 397 More assertions for App 404 Using beforeEach 409 Simulating a change 413 Clearing the input field 417 Simulating a form submission 419 Writing tests for the food lookup app 428 FoodSearch 431 Exploring FoodSearch 433 Writing FoodSearch.test.js 440 In initial state 441 A user has typed a value into the search field 444 Mocking with Jest 449 Mocking Client 452 The API returns results 458 The user clicks on a food item 464 The API returns empty result set 470 Further reading 475 Routing 478 What's in a URL? 478 React Router's core components 481 Building the components of react-router 482 The completed app 482 Building Route 484 Building Link 492 Building Router 498 Building Redirect 504 Using react-router 509 More Route 510 Using Switch 516 Dynamic routing with React Router 519 The completed app 519 The server's API 523 Starting point of the app 526 Using URL params 532 Propagating pathnames as props 540 Dynamic menu items with NavLink 546 Supporting authenticated routes 550 The Client library 551 Implementing login 553 PrivateRoute, a higher-order component 560 Redirect state 565 Recap 567 Further Reading 567 Part II 568 Intro to Flux and Redux 569 Why Flux? 569 Flux is a Design Pattern 570 Flux overview 570 Flux implementations 571 Redux 572 Redux's key ideas 572 Building a counter 573 Preparation 573 Overview 574 The counter's actions 575 Incrementing the counter 576 Decrementing the counter 577 Supporting additional parameters on actions 579 Building the store 581 Try it out 585 The core of Redux 586 Next up 587 The beginnings of a chat app 587 Previewing 587 State 590 Actions 590 Building the reducer() 591 Initializing state 591 Handling the ADD_MESSAGE action 592 Handling the DELETE_MESSAGE action 596 Subscribing to the store 598 createStore() in full 601 Connecting Redux to React 603 Using store.getState() 604 Using store.subscribe() 604 Using store.dispatch() 605 The app's components 606 Preparing App.js 606 The App component 607 The MessageInput component 609 The MessageView component 611 Next up 613 Intermediate Redux 615 Preparation 615 Using createStore() from the redux library 617 Try it out 617 Representing messages as objects in state 618 Updating ADD_MESSAGE 619 Updating DELETE_MESSAGE 622 Updating the React components 623 Introducing threads 625 Supporting threads in initialState 627 Supporting threads in the React components 629 Modifying App 630 Turning MessageView into Thread 631 Try it out 632 Adding the ThreadTabs component 633 Updating App 633 Creating ThreadTabs 635 Try it out 635 Supporting threads in the reducer 636 Updating ADD_MESSAGE in the reducer 636 Updating the MessageInput component 643 Try it out 645 Updating DELETE_MESSAGE in the reducer 645 Try it out 649 Adding the action OPEN_THREAD 649 The action object 649 Modifying the reducer 650 Dispatching from ThreadTabs 651 Try it out 652 Breaking up the reducer function 653 A new reducer() 653 Updating threadsReducer() 656 Try it out 661 Adding messagesReducer() 661 Modifying the ADD_MESSAGE action handler 662 Creating messagesReducer() 663 Modifying the DELETE_MESSAGE action handler 664 Adding DELETE_MESSAGE to messagesReducer() 668 Defining the initial state in the reducers 670 Initial state in reducer() 671 Adding initial state to activeThreadIdReducer() 671 Adding initial state to threadsReducer() 672 Try it out 674 Using combineReducers() from redux 674 Next up 675 Using Presentational and Container Components with Redux 677 Presentational and container components 677 Splitting up ThreadTabs 680 Splitting up Thread 686 Removing store from App 693 Try it out 694 Generating containers with react-redux 695 The Provider component 695 Wrapping App in Provider 696 Using connect() to generate ThreadTabs 697 Using connect() to generate ThreadDisplay 701 Action creators 708 Conclusion 712 Asynchronicity and server communication 713 Using GraphQL 714 Your First GraphQL Query 714 GraphQL Benefits 717 GraphQL vs. REST 718 GraphQL vs. SQL 719 Relay and GraphQL Frameworks 720 Chapter Preview 721 Consuming GraphQL 722 Exploring With GraphiQL 722 GraphQL Syntax 101 727 Complex Types 732 Unions 733 Fragments 734 Interfaces 735 Exploring a Graph 736 Graph Nodes 739 Viewer 741 Graph Connections and Edges 743 Mutations 747 Subscriptions 748 GraphQL With JavaScript 750 GraphQL With React 751 Wrapping Up 753 GraphQL Server 754 Writing a GraphQL Server 754 Special setup for Windows users 754 Game Plan 756 Express HTTP Server 756 Adding First GraphQL Types 759 Adding GraphiQL 762 Introspection 764 Mutation 766 Rich Schemas and SQL 769 Setting Up The Database 770 Schema Design 775 Object and Scalar Types 777 Lists 784 Performance: Look-Ahead Optimizations 787 Lists Continued 790 Connections 793 Authentication 803 Authorization 805 Rich Mutations 810 Relay and GraphQL 814 Performance: N+1 Queries 816 Summary 821 Relay Classic 822 Introduction 822 What We're Going to Cover 823 What We're Building 824 Guide to the Code Structure 828 Relay is a Data Architecture 830 Relay GraphQL Conventions 831 Exploring Relay Conventions in GraphQL 832 Fetching Objects By ID 832 Walking Connections 837 Changing Data with Mutations 842 Relay GraphQL Queries Summary 844 Adding Relay to Our App 844 Quick Look at the Goal 844 A Preview of the Author Page 847 Containers, Queries, and Fragments 848 Validating Our Relay Queries at Compile Time 849 Setting Up Routing 856 Adding Relay to Our Routes 858 App Component 859 AuthorQueries Component 861 AuthorPage Component 862 Try It Out 863 AuthorPage with Styles 866 BooksPage 868 BooksPage Route 869 BooksPage Component 870 BooksPage render() 873 BookItem 874 BookItem Fragment 876 Fragment Value Masking 876 Improving the AuthorPage 879 Changing Data With Mutations 882 Building a Book's Page 883 Book Page Editing 887 Mutations 890 Defining a Mutation Object 891 Inline Editing 896 Conclusion 898 Where to Go From Here 899 React Native 900 Init 901 Routing 903 907 renderScene() 908 configureScene() 911 Web components vs. Native components 914 915 915 916 916 , , and 916 917 917 917 918 Styles 928 StyleSheet 929 Flexbox 931 HTTP requests 953 What is a promise 953 Enter Promises 956 Single-use guarantee 958 Creating a promise 958 Debugging with React Native 960 Where to go from here 962 Appendix A: PropTypes 964 Validators 965 string 966 number 967 boolean 968 function 969 object 970 object shape 971 multiple types 972 instanceOf 973 array 974 array of type 975 node 976 element 977 any type 979 Optional & required props 979 custom validator 980 Appendix B: ES6 983 Prefer const and let over var 983 Arrow functions 984 Modules 987 Object.assign() 990 Template literals 991 The spread operator (...) 992 Enhanced object literals 992 Default arguments 993 Destructuring assignments 994 Appendix C: React Hooks 997 WARNING: Hooks are Alpha 997 Motivation behind Hooks 997 How Hooks Map to Component Classes 998 Using Hooks Requires react "next" 998 useState() Hook Example 999 Our Component is a Function 1002 Reading and Writing State 1002 React Tracks the State 1003 Multiple States 1003 useEffect() Hook Example 1004 Fetch Data and Update State 1006 Performance Concerns When Using Effects 1006 useContext() Hook Example 1007 The Point of Context 1007 useContext() makes context easier to use 1007 Getting a Reference to the Context in a Larger App 1009 useRef() Hook Example 1009 useRef() and forms with input 1010 Using Custom Hooks 1011 Writing Tests for React Hooks 1013 Writing tests for useState() Hook 1014 Writing tests for useEffect() Hook 1015 Writing tests for useRef() Hook 1017 Community Reaction to Hooks 1018 References to the Different types of Hooks 1019 Future of Hooks 1020 More Resources 1021 Changelog 1022 Revision 40 - 2020-01-13 1022 Revision 39 - 2019-01-10 1022 Revision 38 - 2018-12-20 1022 Revision 37 - 2018-12-19 1022 Revision 36 - 2018-10-01 1022 Revision 35 - 2018-04-02 1023 Revision 34 - 2017-10-17 1023 Revision 33 - 2017-08-31 1023 Revision 32 - 2017-06-14 1023 Revision 31 - 2017-05-18 1023 Revision 30 - 2017-04-20 1023 Revision 29 - 2017-04-13 1024 Revision 28 - 2017-04-10 1024 Revision 27 - 2017-03-16 1024 Revision 26 - 2017-02-22 1024 Revision 25 - 2017-02-17 1024 Revision 24 - 2017-02-08 1024 Revision 23 - 2017-02-06 1025 Revision 22 - 2017-02-01 1025 Revision 21 - 2017-01-27 1025 Revision 20 - 2017-01-10 1025 Revision 19 - 2016-12-20 1025 Revision 18 - 2016-11-22 1026 Revision 17 - 2016-11-04 1026 Revision 16 - 2016-10-12 1026 Revision 15 - 2016-10-05 1026 Revision 14 - 2016-08-26 1026 Revision 13 - 2016-08-02 1026 Revision 12 - 2016-07-26 1026 Revision 11 - 2016-07-08 1027 Revision 10 - 2016-06-24 1027 Revision 9 - 2016-06-21 1027 Revision 8 - 2016-06-02 1027 Revision 7 - 2016-05-13 1027 Revision 6 - 2016-05-13 1027 Revision 5 - 2016-04-25 1027 Revision 4 - 2016-04-22 1027 Revision 3 - 2016-04-08 1028 Revision 2 - 2016-03-16 1028 Revision 1 - 2016-02-14 1028