28,79 €
Create large-scale web applications with code that is extensible and easy to understand using React Hooks
React Hooks revolutionize how you manage state and effects in your web applications. They enable you to build simple and concise React.js applications, along with helping you avoid using wrapper components in your applications, making it easy to refactor code.
This React book starts by introducing you to React Hooks. You will then get to grips with building a complex UI in React while keeping the code simple and extensible. Next, you will quickly move on to building your first applications with React Hooks. In the next few chapters, the book delves into various Hooks, including the State and Effect Hooks. After covering State Hooks and understanding how to use them, you will focus on the capabilities of Effect Hooks for adding advanced functionality to React apps. You will later explore the Suspense and Context APIs and how they can be used with Hooks. Toward the concluding chapters, you will learn how to integrate Redux and MobX with React Hooks. Finally, the book will help you develop the skill of migrating your existing React class components, and Redux and MobX web applications to Hooks.
By the end of this book, you will be well-versed in building your own custom Hooks and effectively refactoring your React applications.
This book is for React developers who want to learn how to build applications with Hooks. Developers who are looking to migrate to React for its advanced feature set and capabilities will also find the book useful.
Daniel Bugl is a developer, product designer, and entrepreneur focusing on web technologies. He has a Bachelor of Science degree in business informatics and information systems and is now studying data science at the Vienna University of Technology (TU Wien). He is a contributor to many open source projects and a member of the React community. He also founded and runs his own hardware/software start-up, TouchLay, which helps other companies present their products and services. At his company, he constantly works with web technologies, particularly making use of React and React Hooks.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 438
Veröffentlichungsjahr: 2019
Copyright © 2019 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.
Commissioning Editor: Pavan RamchandaniAcquisition Editor: Heramb BhavsarContent Development Editor: Keagan CarneiroSenior Editor: Mohammed Yusuf ImaratwaleTechnical Editor: Suwarna PatilCopy Editor: Safis EditingProject Coordinator: Manthan PatelProofreader: Safis EditingIndexer: Pratik ShirodkarProduction Designer: Aparna Bhagat
First published: October 2019
Production reference: 1181019
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83864-144-3
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
When Hooks were initially released, I was excited, but also skeptical. Being able to rely only on functions was fantastic. On the other hand, Hooks such asuseEffectrequired the whole React community to rethink how to approach managing side effects.
Hooks made it very easy to handle the most commonplace things, such as rendering and managing state. For such things, most of the time, you can get away with not actually knowing that much about Hooks. Still, now and then, you will need to handle more complex requirements and this requires you to have a deep understanding of when to apply which Hook.
In his book, Daniel starts from the very beginning. Anyone with a basic understanding of React can get started with it. Even so, this book goes very deep and even someone experienced with Hooks will most likely learn something new since Daniel also touches on design decisions and shows basic implementations of the presented concepts. Also, while he covers the theory well, each chapter has plenty of hands-on examples.
Nik GrafReactVienna organizer ReasonConf organizer
Nik Graf initiated the ReactVienna Meetup in 2015. He has created several open source projects, including DraftJs plugins, Polished, and Belle, which all featured at Stripe's Open-Source Retreat in 2016. As a consultant/freelancer, he supports multiple companies with their frontend architecture using React and GraphQL. In addition to that, he produces video courses, which can be found on his personal website: https://www.nikgraf.com.
When React Hooks were released, Nik created a searchable collection of community-created Hooks at https://nikgraf.github.io/react-hooks/.
Daniel Bugl is a developer, product designer, and entrepreneur focusing on web technologies. He has a Bachelor of Science degree in business informatics and information systems and is now studying data science at the Vienna University of Technology (TU Wien). He is a contributor to many open source projects and a member of the React community. He also founded and runs his own hardware/software start-up, TouchLay, which helps other companies present their products and services. At his company, he constantly works with web technologies, particularly making use of React and React Hooks.
Farzad YousefZadeh is a self-taught senior software engineer and an international conference speaker with an academic background in aerospace engineering and astrophysics. He lives in Finland with his wife and their cat. He mainly works with JavaScript and TypeScript on different platforms, but he is most passionate about client-side applications, thriving to solve UI development challenges by studying revolutionary approaches. He is fascinated by tooling around with developmentexperience and automation. He is an active member of the open source community by constantly contributing to OSS, public technical speaking, and volunteering in free educational programs.
Kirill Ezhemenskii is an experienced software engineer, a frontend and mobile developer, a solution architect, and the CTO at a healthcare company. He's a functional programming advocate and an expert in the React stack, GraphQL, and TypeScript. He's also a React native mentor.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Learn React Hooks
Dedication
About Packt
Why subscribe?
Foreword
About Nik Graf
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Code in Action
Conventions used
Get in touch
Reviews
Section 1: Introduction to Hooks
Introducing React and React Hooks
Technical requirements
Principles of React
Motivation for using React Hooks
Confusing classes
Wrapper hell
Hooks to the rescue!
Getting started with React Hooks
Initializing a project with create-react-app
Creating a new project
Starting a project
Deploying a project
Starting with a class component
Setting up the project 
Defining the class component
Example code
Using Hooks instead
Setting up the project
Defining the function component
Example code
Comparing the solutions
Class component
Function component with Hook
Advantages of Hooks
Migrating to Hooks
The Hooks mindset
Rules of Hooks
Overview of various Hooks
Hooks provided by React
Basic Hooks
useState
useEffect
useContext
Additional Hooks
useRef
useReducer
useMemo
useCallback
useLayoutEffect
useDebugValue
Community Hooks
useInput
useResource
Navigation Hooks
Life cycle Hooks
Timer Hooks
Other community Hooks
Summary
Questions
Further reading
Using the State Hook
Technical requirements
Reimplementing the useState function
Problems with our simple Hook implementation
Using a global variable
Defining multiple Hooks
Adding multiple Hooks to our component
Implementing multiple Hooks
Example code
Can we define conditional Hooks?
Example code
Comparing our reimplementation with real Hooks
Alternative Hook APIs
Named Hooks
Hook factories
Other alternatives
Solving common problems with Hooks
Solving conditional Hooks
Always defining the Hook
Splitting up components
Solving Hooks in loops
Using an array
Splitting up components
Solving problems with conditional Hooks
Example code
Summary
Questions
Further reading
Writing Your First Application with React Hooks
Technical requirements
Structuring React projects
Folder structure
Choosing the features
Coming up with an initial structure
Component structure
Implementing static components
Setting up the project 
Implementing users
The Login component
Testing out our component
The Logout component
The Register component
The UserBar component
Example code
Implementing posts
The Post component
The CreatePost component
The PostList component
Putting the app together
Example code
Implementing stateful components with Hooks
Adding Hooks for the users feature
Adjusting UserBar
Adjusting the Login and Register components
Login
Register
Adjusting Logout
Passing the user to CreatePost
Adding Hooks for the posts feature
Adjusting the App component
Adjusting the CreatePost component
Example code
Summary
Questions
Further reading
Section 2: Understanding Hooks in Depth
Using the Reducer and Effect Hooks
Technical requirements
Reducer Hooks versus State Hooks
Problems with the State Hook
Actions
Reducers
The Reducer Hook
Implementing Reducer Hooks
Turning a State Hook into a Reducer Hook
Replacing the user State Hook
Defining actions
Defining the reducer
Defining the Reducer Hook
Replacing the posts State Hook
Defining actions
Defining the reducer
Defining the Reducer Hook
Example code
Merging Reducer Hooks
Ignoring unhandled actions
Example code
Using Effect Hooks
Remember componentDidMount and componentDidUpdate?
Using an Effect Hook
Trigger effect only when certain props change
Trigger effect only on mount
Cleaning up effects
Implementing an Effect Hook in our blog app
Example code
Summary
Questions
Further reading
Implementing React Context
Technical requirements
Introducing React context
Passing down props
Introducing React context
Defining the context
Defining the consumer
Using Hooks
Defining the provider
Nested providers
Example code
Alternative to contexts
Implementing themes
Defining the context
Defining the Context Hooks
Creating the Header component
Using the Header component
Implementing the Context Hook for the Post component
Defining the provider
Dynamically changing the theme
Using a State Hook with the context provider
Implementing the ChangeTheme component
Example code
Using context for global state
Defining StateContext
Defining the context provider
Using StateContext
Refactoring user components
Refactoring post components
Example code
Summary
Questions
Further reading
Implementing Requests and React Suspense
Technical requirements
Requesting resources with Hooks
Setting up a dummy server
Creating the db.json file
Installing the json-server tool
Configuring package.json
Configuring a proxy
Defining routes
Example code
Implementing requests using Effect and State/Reducer Hooks
Requests with Effect and State Hooks
Requests with Effect and Reducer Hooks
Example code
Using axios and react-request-hook
Setting up the libraries
Using the useResource Hook
Using useResource with a Reducer Hook
Handling error state
Implementing post creation
Implementing registration
Implementing login
Example code
Preventing unnecessary re-rendering with React.memo
Implementing React.memo for the Post component
Example code
Implementing lazy loading with React Suspense
Implementing React.Suspense
Implementing React.lazy
Example code
Summary
Questions
Further reading
Using Hooks for Routing
Technical requirements
Creating multiple pages
Creating the HeaderBar component
Creating the HomePage component
Creating the PostPage component
Testing out the PostPage
Example code
Implementing routing
Defining routes
Defining links
Defining links to the posts
Defining the links to the main page
Adjusting the CREATE_POST action
Example code
Using routing Hooks
Overview of Navi's Hooks
The useNavigation Hook
The useCurrentRoute Hook
The useLoadingRoute Hook
Programmatic navigation
Accessing route information
Example code
Summary
Questions
Further reading
Using Community Hooks
Technical requirements
Exploring the input handling Hook 
Implementing Input Hooks in our blog app
The Login component
The Register component
The CreatePost component
Example code
React life cycles with Hooks 
The useOnMount Hook
The useOnUnmount Hook
The useLifecycleHooks Hook
The useMergeState Hook
Example code
Various useful Hooks 
The usePrevious Hook
Timer Hooks
The useInterval Hook
useTimeout Hook
The Online Status Hook
Data manipulation Hooks
The useBoolean Hook
The useArray Hook
The useCounter Hook
Focus and Hover Hooks 
The useFocus Hook
The useHover Hook
Example code
Responsive design with Hooks
Responsively hiding components
Example code
Undo/Redo with Hooks
Implementing Undo/Redo in our post editor
Debouncing with Hooks
Debouncing changes in our post editor
Example code
Finding other Hooks
Summary
Questions
Further reading
Rules of Hooks
Technical requirements
Calling Hooks
Order of Hooks
Names of Hooks
Enforcing the rules of Hooks
Setting up eslint-plugin-react-hooks
Example code
Dealing with useEffect dependencies
Automatically fixing warnings with eslint
Example code
Summary
Questions
Further reading
Building Your Own Hooks
Technical requirements
Extracting custom Hooks
Creating a useTheme Hook
Creating global state Hooks
Defining the useUserState Hook
Defining the usePostsState Hook
Creating a useDispatch Hook
Creating API Hooks
Creating a useDebouncedUndo Hook
Exporting our custom Hooks
Example code
Using our custom Hooks
Using the useTheme Hook
Using the global state Hooks
Adjusting the UserBar component
Adjusting the Login component
Adjusting the Register component
Adjusting the Logout component
Adjusting the CreatePost component
Adjusting the PostList component
Using the API Hooks
Adjusting the ChangeTheme component
Adjusting the Register component
Adjusting the Login component
Adjusting the CreatePost component
Using the useDebouncedUndo Hook
Example code
Interactions between Hooks
Creating a local Register Effect Hook
Creating a local Login Effect Hook
Example code
Testing Hooks
Using the React Hooks Testing Library
Testing simple Hooks
Creating the useCounter Hook
Testing the useCounter Hook result
Testing useCounter Hook actions
Testing the useCounter initial value
Testing reset and forcing re-rendering
Testing Context Hooks
Creating the ThemeContextWrapper
Testing the useTheme Hook
Creating the StateContextWrapper
Testing the useDispatch Hook
Testing the useUserState Hook
Testing the usePostsState Hook
Testing async Hooks
The async/await construct
Testing the useDebouncedUndo Hook
Running the tests
Example code
Exploring the React Hooks API
The useState Hook
The useEffect Hook
The useContext Hook
The useReducer Hook
The useMemo Hook
The useCallback Hook
The useRef Hook
The useImperativeHandle Hook
The useLayoutEffect Hook
The useDebugValue Hook
Summary
Questions
Further reading
Section 3: Integration and Migration
Migrating from React Class Components
Technical requirements
Handling state with class components
Designing the app structure
Initializing the project
Defining the app structure
Defining the components
Defining the Header component
Defining the AddTodo component
Defining the TodoList component
Defining the TodoItem component
Defining the TodoFilter component
Implementing dynamic code
Defining the API code
Defining the StateContext
Making the App component dynamic
Making the AddTodo component dynamic
Making the TodoList component dynamic
Making the TodoItem component dynamic
Making the TodoFilter component dynamic
Example code
Migrating from React class components
Migrating the TodoItem component
Migrating the TodoList component
Migrating the TodoFilter component
Migrating TodoFilterItem
Migrating TodoFilter
Migrating the AddTodo component
Migrating the App component
Defining the actions
Defining the reducers
Defining the filter reducer
Defining the todos reducer
Defining the app reducer
Migrating the component
Example code
Trade-offs of class components
Summary
Questions
Further reading
Redux and Hooks
Technical requirements
What is Redux?
The three principles of Redux
Single source of truth
Read-only state
State changes are processed with pure functions
Handling state with Redux
Installing Redux
Defining state, actions, and reducers
State
Actions
Reducers
Setting up the Redux store
Example code
Defining action types
Defining action creators
Defining synchronous action creators
Defining asynchronous action creators
Adjusting the store
Adjusting reducers
Setting the initial state in Redux reducers
Connecting components
Connecting the AddTodo component
Connecting the TodoItem component
Connecting the TodoList component
Adjusting the TodoList component
Connecting the TodoFilter component
Connecting the App component
Setting up the Provider component
Example code
Using Redux with Hooks
Using the dispatch Hook
Using Hooks for the AddTodo component
Using Hooks for the App component
Using Hooks for the TodoItem component
Using the Selector Hook
Using Hooks for the TodoList component
Using Hooks for the TodoFilter component
Example code
Creating reusable selectors
Setting up reselect
Memoizing selectors that only depend on state
Example code
Using the store Hook
Migrating a Redux application
Trade-offs of Redux
Summary
Questions
Further reading
MobX and Hooks
Technical requirements
What is MobX?
Handling state with MobX
Installing MobX
Setting up the MobX store
Defining the Provider component
Connecting components
Connecting the App component
Connecting the TodoList component
Connecting the TodoItem component
Connecting the AddTodo component
Connecting the TodoFilter component
Example code
Using MobX with Hooks
Defining a store Hook
Upgrading components to Hooks
Using Hooks for the App component
Using Hooks for the TodoList component
Using Hooks for the TodoItem component
Using Hooks for the AddTodo component
Using Hooks for the TodoFilter component
Example code
Using the local store Hook
Example code
Migrating a MobX application
The trade-offs of MobX
Summary
Questions
Further reading
Assessments
Answers to questions
Chapter 1: Introducing React and React Hooks
Chapter 2: Using the State Hook
Chapter 3: Writing Your First Application with React Hooks
Chapter 4: Using the Reducer and Effect Hooks
Chapter 5: Implementing React Context
Chapter 6: Implementing Requests and React Suspense
Chapter 7: Using Hooks for Routing
Chapter 8: Using Community Hooks
Chapter 9: Rules of Hooks
Chapter 10: Building Your Own Hooks
Chapter 11: Migrating from React Class Components
Chapter 12: Redux and Hooks
Chapter 13: MobX and Hooks
Other Books You May Enjoy
Leave a review - let other readers know what you think
React is a JavaScript library for building efficient and extensible web applications. React is developed by Facebook and is used in many large-scale web applications, such as Facebook, Instagram, Netflix, and WhatsApp Web.
React Hooks were introduced in the React 16.8 release and solve many common problems with React projects. Hooks make components less complex, more concise, and easier to read and refactor. Furthermore, they make many React features much easier to use and understand, and we avoid having to use wrapper components.
This book is the definitive guide to learning React Hooks. You are going to learn all the facets of React Hooks for managing state and effects in React components, as well as using other React features, such as context, via Hooks. With practical examples, you are going to learn how to develop large-scale and efficient applications with code that is extensible and easy to understand.
The book also delves into advanced concepts, such as using Hooks in combination with libraries like Redux and MobX. Furthermore, you are going to learn when and how existing projects can be efficiently migrated to React Hooks.
The book is intended for web developers at any level of expertise with JavaScript and the React framework. The book will also cater to developers who have been migrating to React for its advanced feature set and capabilities.
Chapter 1, Introducing React and React Hooks, covers the fundamental principles of React and React Hooks, what they are and why to use them. We then learn about the functionality of Hooks by introducing the State Hook as an alternative to React state in class components. Finally, we introduce the kinds of Hooks React provides and introduce a couple of Hooks that we are going to learn about throughout the book.
Chapter 2, Using the State Hook, explains how Hooks work in depth by reimplementing the useState Hook. By doing so, we find out that there are certain limitations of Hooks. We are then going to compare our reimplementation of a Hook with real Hooks. Furthermore, we introduce alternative Hook APIs and discuss the problems they have. Finally, we learn how to solve common problems with Hooks, such as conditional Hooks and Hooks in loops.
Chapter 3, Writing Your First Application with React Hooks, takes what we learned from the first two chapters and puts it into practice by developing a blog application using React Hooks, specifically the State Hook. In this chapter, we also learn how to structure React projects in a way that scales well.
Chapter 4, Using the Reducer and Effect Hooks, moves on from learning about the simple State Hook and using it in practice. We are going to learn about the other two main Hooks predefined by the React library: the Reducer and Effect Hooks. We first learn when we should use a Reducer Hook instead of a State Hook. Then we learn how to turn our existing State Hook into a Reducer Hook to get an idea of the concept. Finally, we learn how to use Effect Hooks for more advanced functionality.
Chapter 5, Implementing React Context, explains React context and how it can be used in our application. Then we implement React context in our blog application to provide theming functionality and global state using Context Hooks.
Chapter 6, Implementing Requests and React Suspense, covers requesting resources from a server with Hooks using an Effect Hook and a State or Reducer Hook. Then we learn how to use React.memo to prevent unnecessary component re-renders. Finally, we learn about React Suspense, which can be used to defer rendering until a condition is met, also called lazy loading.
Chapter 7, Using Hooks for Routing, explains how to use Hooks to implement routing in our blog application. We learn about Navi, a routing library for React that makes use of Hooks and Suspense. We start by implementing pages in our application, then define routes, and finally move on to implementing routing Hooks.
Chapter 8, Using Community Hooks, explains that the React community has already developed various libraries that make use of Hooks. In this chapter, we learn about implementing various Hooks from the community, as well as where to find more of them. We first learn about the input handling Hook. Next, we learn how to replace React life cycle methods with Hooks. Then, we learn about various useful Hooks and responsive design with Hooks. Furthermore, we learn how to implement undo/redo functionality using Hooks. Finally, we learn where to find other Hooks provided by the community.
Chapter 9, Rules of Hooks, covers the rules of Hooks. Having a grasp on the rules of Hooks is very important for building our own Hooks, which we are going to do in the next chapter. We also learn about the limitations of Hooks in depth and discover what we need to watch out for. Finally, we learn how to enforce the rules of Hooks using a linter.
Chapter 10, Building Your Own Hooks, moves on from the basic concepts of Hooks. We are now going to build our own Hooks. We start by extracting a custom Hook from an existing function of our blog application, and then we learn how to use our custom Hook. Next, we learn about passing information between Hooks. Finally, we learn about the React Hooks API and additional Hooks we can use to build our own Hooks. At the end of this chapter, our application will be fully powered by Hooks!
Chapter 11, Migrating from React Class Components, covers state handling with React class components. We start by implementing a simple ToDo application with class components. Then, we learn how to migrate an existing project using class components to a Hook-based implementation. Finally, we learn about the trade-offs of using class components versus Hooks and a strategy to efficiently migrate existing projects.
Chapter 12, Redux and Hooks, explains state handling with Redux. We start by migrating our existing ToDo application to Redux, and then we learn how to use Redux with Hooks. Furthermore, we learn how to migrate an existing Redux application to Hooks. Finally, we learn about the trade-offs of using Redux.
Chapter 13, MobX and Hooks, covers state handling with MobX. We start by migrating our existing ToDo application to MobX. Then we learn how to use MobX with Hooks. Furthermore, we learn how to migrate an existing MobX application to Hooks. Finally, we learn about the trade-offs of using MobX.
We assume that you have already worked with React in some way, although this book should be understandable for complete beginners of React as well.
Please note that it is highly recommended that you write the code on your own. Do not simply run the code examples that are provided. It is important to write the code yourself in order to learn and understand it properly. However, if you run into any issues, you can always refer to the code example.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
Support
tab.
Click on
Code Downloads
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learn-React-Hooks. In case there's an update to the code, it will be updated on the existing 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!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781838641443_ColorImages.pdf.
Visit the following link to check out videos of the code being run:
http://bit.ly/2Mm9yoC
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
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, selecting your book, clicking on the Errata Submission Form link, and entering the details.
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.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
In the first part of the book, we will introduce and cover the basics of React and React Hooks, including why and how to use them. Following this, we will use our knowledge gained in a practical setting, to create a blog application using React Hooks.
In this section, we will cover the following chapters:
Chapter 1
,
Introducing React and React Hooks
Chapter 2
,
Using the State Hook
Chapter 3
,
Writing Your First Application with React Hooks
React is a JavaScript library that can be used to build efficient and extensible web applications. React was developed by Facebook, and is used in many large-scale web applications, such as Facebook, Instagram, Netflix, and WhatsApp Web.
In this book, we are going to learn how to build complex and efficient user interfaces with React, while keeping the code simple and extensible. Using the new paradigm of React Hooks, we can greatly simplify dealing with state management and side effects in web applications, ensuring the potential for growing and extending the application later on. We are also going to learn about React context and React Suspense, as well as how they can be used with Hooks. Afterward, we are going to learn how to integrate Redux and MobX with React Hooks. Finally, we are going to learn how to migrate from existing React class components, Redux, and MobX web applications, to React Hooks.
In the first chapter of this book, we are going to learn about the fundamental principles of React and React Hooks. We start by learning what React and React Hooks are, and why we should use them. Then, we move on to learn about the functionality of Hooks. Finally, we give an introduction to the kinds of Hooks that are provided by React, and a couple of Hooks that we are going to learn about throughout the book. By learning the fundamentals of React and React Hooks, we will be better able to understand the concepts that will be introduced in this book.
The following topics will be covered in this chapter:
Learning about the fundamental principles of React
Motivating the need for React Hooks
Getting started with React Hooks
Giving an overview of various Hooks
A fairly recent version of Node.js should already be installed (v11.12.0, or higher). The npm package manager for Node.js also needs to be installed.
The code for this chapter can be found on the GitHub repository: https://github.com/PacktPublishing/Learn-React-Hooks/tree/master/Chapter01.
Check out the following video to see the code in action:
http://bit.ly/2Mm9yoC
Now, let's get started with the chapter.
React's three fundamental principles make it easy to write code, encapsulate components, and share code across multiple platforms. Instead of reinventing the wheel, React always tries to make use of existing JavaScript features as much as possible. As a result, we are going to learn software design patterns that will be applicable in many more cases than just designing user interfaces.
React always strives to make the developer experience as smooth as possible, while ensuring that it is kept performant enough, without the developer having to worry too much about how to optimize performance. However, throughout the years of using React, a couple of problems have been identified.
Let's take a look at these problems in detail in the following sections.
In the past, we had to use class components with special functions called life cycle methods, such as componentDidUpdate, and special state-handling methods, such as this.setState, in order to deal with state changes. React classes, and especially the this context, which is a JavaScript object, are hard to read and understand for both humans and machines.
this is a special keyword in JavaScript that always refers to the object that it belongs to:
In a method,
this
refers to the class object (instance of the class).
In an event handler,
this
refers to the element that received the event.
In a function or when standing alone,
this
refers to the global object. For example, in a browser, the global object is the
Window
object.
In strict mode,
this
is
undefined
in a function.
Additionally, methods such as
call()
and
apply()
can change the object that
this
refers to, so it can refer to any object.
For humans, classes are hard because this always refers to different things, so sometimes (for example, in event handlers) we need to manually rebind it to the class object. For machines, classes are hard, because the machines do not know which methods in a class will be called, and how this will be modified, making it hard to optimize performance and remove unused code.
Furthermore, classes sometimes require us to write code in multiple places at once. For example, if we want to fetch data when the component renders, or the data updates, we need to do this using two methods: once in componentDidMount, and once in componentDidUpdate.
To give an example, let's define a class component that fetches data from an Application Programming Interface (API):
First, we define our class component by extending the
React.Component
class:
class Example extends React.Component {
Then, we define the
componentDidMount
life cycle method, where we pull data from an API:
componentDidMount () { fetch(`http://my.api/${this.props.name}`) .then(...) }
However, we also need to define the
componentDidUpdate
life cycle method in case the
name
prop changes. Additionally, we need to add a manual check here, in order to ensure that we only re-fetch data if the
name
prop changed, and not when other props change:
componentDidUpdate (prevProps) { if (this.props.name !== prevProps.name) { fetch(`http://my.api/${this.props.name}`) .then(...) } }}
To make our code less repetitive, we could define a separate method called
fetchData
, in order to fetch our data, as follows:
fetchData () { fetch(`http://my.api/${this.props.name}`) .then(...) }
Then, we could call the method in
componentDidMount
and
componentDidUpdate
:
componentDidMount () { this.fetchData() } componentDidUpdate (prevProps) { if (this.props.name !== prevProps.name) { this.fetchData()
} }
However, even then we still need to call fetchData in two places. Whenever we update arguments that are passed to the method, we need to update them in two places, which makes this pattern very prone to errors and future bugs.
As we can see, React Hooks solve many problems, especially of larger web applications. Hooks were added in React 16.8, and they allow us to use state, and various other React features, without writing a class. In this section, we are going to start out by initializing a project with create-react-app, then we will define a class component, and finally we will write the same component as a function component using Hooks. By the end of this section, we will have talked about the advantages of Hooks, and how we would go about migrating to a Hook-based solution.
To initialize a React project, we can use the create-react-app tool, which sets up the environment for React development, including the following:
Babel, so that we can use the JSX and ES6 syntaxes
It even includes language extras beyond ES6, such as the object spread operator, which we are going to make use of later
Additionally, we could even use TypeScript and Flow syntax
Furthermore, create-react-app sets up the following:
Autoprefixed
Cascading Style Sheets
(
CSS
), so that we do not need browser-specific prefixes such as
-webkit
A fast interactive unit test runner with code coverage reporting
A live development server, which warns us about common mistakes
A build script, which bundles JavaScript, CSS, and images for production, including hashes and sourcemaps
An offline-first service worker and a web app manifest to meet all criteria of a
Progressive Web App
(
PWA
)
Hassle-free updates for all the tools that have been previously listed
As we can see, the create-react-app tool makes React development a lot easier for us. It is the perfect tool for us to use in order to learn about React, as well as for deploying React applications in production.
In order to set up a new project, we run the following command, which creates a new directory named <app-name>:
>
npx create-react-app <app-name>
We are now going to create a new project using create-react-app. Run the following command to create a new React project for the first example of the first chapter:
>
npx create-react-app chapter1_1
Now that we have initialized our project, let's move on to starting the project.
In order to start a project in development mode, we have to run the npm start command. Run the following command:
>
npm start
Now, we can access our project by opening http://localhost:3000 in our browser:
As we can see, with create-react-app, it is quite easy to set up a new React project!
To build a project for production deployments, we simply run the build script:
Run the following command to build the project for production deployment:
>
npm run-script build
We can then serve our static build folder with a web server, or by using the
serve
tool. First, we have to install it:
>
npm install -g serve
Then, we can run the
serve
command, as follows:
>
serve -s build
Now, we can access the same app by opening http://localhost:5000 in our browser. Please note that the serve tool does not automatically open the page in your browser.
After learning about create-react-app, we are now going to write our first component with React.
First, we start out with a traditional React class component, which lets us enter a name, which we then display in our app.
As mentioned before, we are going to use create-react-app to initialize our project. If you have not done so already, run the following command now:
>
npx create-react-app chapter1_1
Next we are going to define our app as a class component.
The example code can be found in the Chapter01/chapter1_1 folder.
Just run npm install in order to install all dependencies, and npm start to start the application; then visit http://localhost:3000 in your browser (if it did not open automatically).
After using a traditional class component to write our app, we are going to write the same app using Hooks. As before, our app is going to let us enter a name, which we then display in our app.
We now start by setting up the project.
Again, we use create-react-app to set up our project:
>
npx create-react-app chapter1_2
Let's get started with defining a function component using Hooks now.
Now, we define the same component as a function component:
First, we remove all code from the
src/App.js
file.
Next, in
src/App.js
, we import React, and the
useState
Hook:
import React, { useState } from 'react'
