Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Learn React Hooks: Build and refactor modern React.js applications using Hooks
Learn React Hooks: Build and refactor modern React.js applications using Hooks
Learn React Hooks: Build and refactor modern React.js applications using Hooks
Ebook870 pages5 hours

Learn React Hooks: Build and refactor modern React.js applications using Hooks

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Create large-scale web applications with code that is extensible and easy to understand using React Hooks

Key Features
  • Explore effective strategies for migrating your state management from Redux and MobX to React Hooks
  • Integrate Hooks with React features such as Context and Suspense to add advanced functionality to your web apps
  • Create complex applications by combining multiple hooks
Book Description

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.

What you will learn
  • Understand the fundamentals of React Hooks and how they modernize state management in React apps
  • Build your own custom Hooks and learn how to test them
  • Use community Hooks for implementing responsive design and more
  • Learn the limitations of Hooks and what you should and shouldn’t use them for
  • Get to grips with implementing React context using Hooks
  • Refactor your React-based web application, replacing existing React class components with Hooks
  • Use state management solutions such as Redux and MobX with React Hooks
Who this book is for

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.

LanguageEnglish
PublisherPackt Publishing
Release dateOct 18, 2019
ISBN9781838640514
Learn React Hooks: Build and refactor modern React.js applications using Hooks
Author

Daniel Bugl

Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.

Related to Learn React Hooks

Related ebooks

Computers For You

View More

Reviews for Learn React Hooks

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Learn React Hooks - Daniel Bugl

    Learn React Hooks

    Learn React Hooks

    Build and refactor modern React.js applications using Hooks

    Daniel Bugl

    BIRMINGHAM - MUMBAI

    Learn React Hooks

    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 Ramchandani

    Acquisition Editor: Heramb Bhavsar

    Content Development Editor: Keagan Carneiro

    Senior Editor: Mohammed Yusuf Imaratwale

    Technical Editor: Suwarna Patil

    Copy Editor: Safis Editing

    Project Coordinator: Manthan Patel

    Proofreader: Safis Editing

    Indexer: Pratik Shirodkar

    Production 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

    To my family and friends for supporting me during the creation of this book.

    To my father, who has supported me throughout my whole life.

    To my co-founder, Georg Schelkshorn, who runs an amazing company with me. Thank you for taking care of business while I was writing this book.

    To my amazing girlfriend, Junxian Wang, for improving my life in many ways, for making me more productive, and for always taking care of me. I love you so much.

    Without you, all of this would not have been possible.

    – Daniel Bugl

    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.

    Why subscribe?

    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. 

    Foreword

    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 as useEffect required 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 Graf

    ReactVienna organizer

    ReasonConf organizer

    About Nik Graf

    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/.

    Contributors

    About the author

    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.

    I want to thank the people involved in the production of this book, my co-founder, Georg Schelkshorn; my family and friends; and my girlfriend, Junxian Wang.

    About the reviewers

    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 development

    experience 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.

    Packt is searching for authors like you

    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.

    Table of Contents

    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

    Preface

    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.

    Who this book is for

    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.

    What this book covers

    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.

    To get the most out of this book

    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.

    Download the example code files

    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!

    Download the color images

    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.

    Code in Action

    Visit the following link to check out videos of the code being run:

    http://bit.ly/2Mm9yoC

    Conventions used

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

    CodeInText: Indicates code words in text, folder names, filenames, file extensions, pathnames, dummy URLs, and user input. Here is an example: JavaScript classes provide a render method, which returns the user interface (usually via JSX).

    A block of code is set as follows:

    class Example extends React.Component {

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

        constructor (props) {

            super(props)

            this.state = { name: '' }

    this.handleChange = this.handleChange.bind(this)

        }

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

    > npm run-script build

    Bold: Indicates a new term, an important word, or words that you see onscreen. Here is an example: " Throughout this chapter, we are also going to learn about JSX, and new JavaScript features that have been introduced in ES6, up to ES2018."

    In blocks of code, we use bold formatting to highlight changes in the code. Usually, we highlight new code using bold. If specified, we might also indicate which parts of code should be deleted by using bold formatting.

    Warnings or important notes appear like this.

    Tips and tricks 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, 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

    Enjoying the preview?
    Page 1 of 1