Designing React Hooks the Right Way - Fang Jin - E-Book

Designing React Hooks the Right Way E-Book

Fang Jin

0,0
31,19 €

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

Mehr erfahren.
Beschreibung

React hook creates a unique solution for using states in function components to orchestrate UI communication. They provide you with an easy interface to write custom data management solutions with low development and maintenance costs. Understanding how Hooks are designed enables you to use them more effectively, and this book helps you to do just that.
This book starts with a custom-crafted solution to reveal why Hooks are needed in the first place. You will learn about the React engine and discover how each built-in Hook can manage a persistent value by hooking into it. You will walk through the design and implementation of each hook with code so that you gain a solid understanding. Finally, you'll get to grips with each Hook's pitfalls and find out how to effectively overcome them.
By the end of this React book, you'll have gained the confidence to build and write Hooks for developing functional and efficient web applications at scale.

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

EPUB
MOBI

Seitenzahl: 341

Veröffentlichungsjahr: 2022

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



Designing React Hooks the Right Way

Explore design techniques and solutions to debunk the myths about adopting states using React Hooks

Fang Jin

BIRMINGHAM—MUMBAI

Designing React Hooks the Right Way

Copyright © 2022 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.

Associate Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Aaron Tanna

Senior Editor: Sofi Rogers

Content Development Editor: Rakhi Patel

Technical Editor: Joseph Aloocaran

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Subalakshmi Govindhan

Production Designer: Alishon Mendonca

Marketing Coordinator: Teny Thomas

First published: December 2021

Production reference: 1101221

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80323-595-0

www.packt.com

To my wife, Maggie, for her love, care, and support for the whole family, and to my two wonderful kids, Sophia and Lucas, for their curiosity and inspiration. To my parents, Qiang and Yunxia, for the sacrifices they made for me. To everyone else who has supported me.

To my grandpa, Jingzhen Jin, as my life's mentor and role model.

– Fang Jin

Foreword

I have known Fang professionally and personally. He has a genuine personality and is an excellent technologist. We have built multiple applications together for one of the major financial firms where he was UI/UX Lead and Architect. His designed & developed generic framework has been used by many applications in our organization. His fondness and expertise in UI/UX were evident to everyone, and he is always enthusiastic in developing new components and cognizant about newer technologies in UI space. Personally, I have not only learnt from him about using the available technology as-is but also understanding it in depth to grow your knowledge. His years of freelancing work and contribution in UI open-source community is incredible and we always anticipated that he will be a big help in this global UI community, which is coming out now by his book. The book will surely benefit many people.

Sagar Kale

Technology Manager, Deutsche Bank

Contributors

About the author

Fang Jin is a software engineer who makes reusable and scalable web modules that can be applied to modern browsers and devices. He is an engineering hobbyist with interests ranging from economics and philosophy to software development, architecture, and team development. Fang is a lifelong learner and throughout his journey, he has helped organizations and teams adopt UI frameworks to achieve consistent branding and look and feel across departments so that they can save costs and boost efficiency. In his free time, he likes swimming and surfing YouTube.

While the task of writing a book may seem like a personal adventure, this book simply could not have happened without the editorial team.

I especially want to thank my Editors, Sofi Rogers and Rakhi Patel; you've shown me how a book should be written, and your insights have sharpened each chapter. I also want to thank my Product Managers, Pavan Ramchandani and Aaron Tanna, who actually made the book possible. Since the past 8 years, I have been a loyal reader of the books published by Packt and it makes me happy that I could contribute to Packt Publishing from my end.

About the reviewers

Mikhail Sakhniuk is a software engineer with high proficiency in JavaScript, React, and React Native. He has more than 5 years of experience in developing web and mobile applications. He has experience with start-ups, fintech, and product companies that have more than 20 million users. Currently, Mikhail is working at Miro as a frontend engineer. Also, he owns and maintains a few open source projects. His experience and skills are shared via articles and books. 

Michael Asiedu is a full stack JavaScript developer who is hellbent on creating radical outcomes and web apps that scale. His passion for coding, books, and writing has fueled the release of great technical articles and ebooks in the tech community. Before entering software development, he worked in digital marketing, where he co-founded a digital marketing agency with three of his high school friends. Michael has a solid JavaScript background and he sees himself venturing into the Web 3.0 industry. He is a big advocate of open source.

Table of Contents

Preface

Chapter 1: Introducing the Function Component

History of UI components

jQuery

Angular

React

LitElement

Building an app with components

Multiple pages

Introducing the function component

Function props

Children prop

Parent and child

Writing a function component

Example of a function component

Summary

Questions and answers

Appendix

Appendix A – How many component types does React support?

Chapter 2: Crafting States in Functions

Technical requirements

Crafting a state in a function component

Requesting a new update

Making a value persistent

Support multiple states

Listen to a value change

Performing a task at the mount

Applying states to single-page application

How states work with UI

Summary

Questions and answers

Chapter 3: Hooking into React

Creating a good state solution

Introducing a React Hook

Updating a function component

Creating a Hook at the mount

Obtaining a Hook at the update

Using a Hook

What is a Hook?

A hook is a function

A hook's calling order

Conditional hook issue

Avoiding conditional hooks

Summary

Questions and answers

Appendix

Appendix A – React Fiber

Appendix B – Current and WorkInProgress Scenes

Chapter 4: Use State to Jumpstart Components

State in React

useState design

useState data structure

Mounting a state

Dispatching an action

Updating a state

Returning the hook

A walkthrough of useState

Dispatching states

Comparing states

Multiple dispatches

Test driving the useState hook

Letting a child drive

Lifting up to the parent

useState examples

Making an avatar component

Making a custom tooltip component

Summary

Questions and answers

Appendix

Appendix A – Skipping the dispatch

Appendix B – Bailing out an update

Chapter 5: Use Effect to Handle Side Effects

What is a side effect?

Introducing passive effects

Understanding useEffect design

The useEffect hook's data structure

Mounting an effect

Updating an effect

Scheduling effects

Flushing effects

A walk-through of the useEffect hook

Creating effects

Creating and destroying

Test driving the useEffect hook

Missing dependencies

Infinite loops

useEffect examples

Finding the window size

Fetching an API resource

Summary

Questions and answers

Appendix

Appendix A – React side effects

Appendix B - Flushing passive effects

Appendix C – Is a dispatch asynchronous?

Chapter 6: Use Memo to Boost Performance

Performance degradation

Reusing a previous assignment

Understanding the useMemo design

Reusing a last assignment

Assignment value type

The myth of skipping an update

Test-Driving useMemo

useMemo examples

Clicking to search

Debouncing the search

Summary

Questions

Appendix

Appendix A – Not a Classical Memorization

Appendix B – Skipping a Child Update

Chapter 7: Use Context to Cover an Area

What is an area update?

Props approach

Combined dispatch approach

Introducing the React context

Understanding the useContext design

useContext data structure

useContext workflow

Test driving useContext

Changing the context value

useContext examples

Theme context

Table context

Summary

Questions and answers

Appendix

Appendix A – Propagating a context

Appendix B – Context scope and value

Chapter 8: Use Ref to Hide Stuff

Accessing DOM elements

Attach and de-attach

Understanding useRef design

State without an update

Test driving useRef

Controlling a child ref

useRef examples

Clicking outside the menu

Avoiding memory leaks

Setting up a mule

Locating the current value

Summary

Questions and answers

Appendix

Appendix A – Callback ref

Appendix B – Forward ref

Chapter 9: Use Custom Hooks to Reuse Logic

Reviewing React hooks

Making a new hook

Writing a custom hook

useToggle

Usages

References

useWindow

Usages

References

useAsync

Usages

References

useDebounced

Usages

useClickOutside

Usages

References

useCurrent

Usages

References

useProxy

Usages

References

Summary

Questions and answers

Chapter 10: Building a Website with React

Exploring functions of React

Embracing JavaScript ES6

Arrow function

Spread and rest

Object enhancement

Template strings

Destructuring

let and const

Modules

Symbol

Adopting CSS-in-JS approach

styled-SX

styled-components

Going from HTML to JSX

Props

Children

Element type

React element

Summary

Questions and answers

Why subscribe?

Other Books You May Enjoy

Preface

React has been my main development tool lately. In my experience both as a developer and a computer user, I found most of what I love in the end is non-heavy stuff. While big names come and go often, there're certain things left behind. For instance, the way to build a website has been reshaped and refined over the past twenty years, but the general process of building it hasn't changed much. You still need to create an HTML file, design the layout, and host it somewhere on a server.

When it comes to the user interface (UI), there's another topic that can benefit you in a similar way. That is state. From jQuery and Angular to React, from the web to other non-desktop platforms (such as Electron or React Native), no matter where you go, there's a technical question that you need to answer now – how does the screen know there's a change to apply? When I was back in college, I never asked this type of question. I generally assumed the computer just worked that way.

Of course, now I know the computer works that way because someone made it. What's fascinating about the UI is when the state gets in the picture. Back in the early days, we didn't talk about state at all. But now state is everywhere, although there's still no textbook definition for it or how we should learn it in the first place. Suffice to say, state is still a relatively young topic in the web development industry.

In this book, I'll attempt, by using React as the underlying technology, to explore and learn how states are introduced and implemented. I hope, by doing that, we will have a better picture in the end to answer the question – how is a render engine driven by states?

Who this book is for

The ideal reader of this book is an engineer who has been writing JavaScript for a few years but doesn't necessarily have experience with React and/or the function component. For readers with less JavaScript experience, we include a live playground via CodePen so that you can experiment with each topic in no time.

If you do have experience with React, or even Hooks, that's fine; this book will show you how Hooks are implemented within the function component. Moreover, a stripped-down version of the React source code pertaining to each Hook is also included in each chapter, so you will get a deeper understanding if you are an experienced React programmer.

What this book covers

Chapter 1, Introducing the Function Component, explains what a function component is with an explanation of its props and the basic parent/child relationship. You will then get some tips on how to write a function component. At the end of the chapter, you will see a practical function component example, Nav.

Chapter 2, Crafting States in Functions, shows how to craft a special variable called state in function components. We will see what benefits a state can provide, including requesting a new update and listening to a value change. We will also see an example of applying a state to a Single Page Application (SPA). We will also take a close look at what role states play in the UI.

Chapter 3, Hooking into React, goes through the challenges we face when creating a good state solution, and then we'll see how React architects provide the solution with the underlying Hook. We will then introduce Hooks, learn about their calling order, and learn how to avoid running into the conditional Hook issue in real applications.

Chapter 4, Use State to Jumpstart Components, covers built-in Hooks, starting with the useState Hook. We will first explain how state is used in React and then walk through the data structure and source code behind useState, and we'll also describe common usages of dispatching states. We'll give useState a test drive and provide two practical examples of applying useState to the Avatar and Tooltip components.

Chapter 5, Use Effect to Handle Side Effects, introduces side effects, walks through the data structure and source code behind useEffect, and provides various scenarios in which you invoke effects. We will also demonstrate a couple of pitfalls of using useEffect and ways to avoid them. And we'll use useEffect in two practical examples, Window Size and a Fetch API.

Chapter 6, Use Memo to Boost Performance, explains how we can run into performance degradation issues in a typical web application. Then we will walk through the design and source code behind useMemo and describe various ways of reusing a value conditionally. We'll then apply the optimization technique to two common cases, clicking to search and debouncing the search.

Chapter 7, Use Context to Cover an Area, introduces an area updates and how React contexts are used to share a value to an area. Then, we will walk through the data structure and source code behind useContext to consume the shared value. At the end of the chapter, we'll provide two practical examples of applying contexts to a Theme and a Table.

Chapter 8, Use Ref to Hide Stuff, explains how to access a DOM element via a ref, and we'll walk through the design and source code behind the useRef Hook. We will also describe how to work with a persistent value without dispatching an update. Finally, we'll apply refs to a couple of practical problems, such as clicking outside of the menu, avoiding memory leaks, setting up a mule, and locating the current value.

Chapter 9, Use Custom Hooks to Reuse Logic, gathers all the Hooks we have learned about so far and explains how to create a custom Hook for our own needs. We will introduce custom Hooks and then write a couple of custom Hooks step by step, including useToggle, useWindow, useAsync, useDebounced, useClickOutside, useCurrent, and useProxy.

Chapter 10, Building a Website with React, discusses React in general, especially the role React plays in web development. We will approach this topic from three perspectives to see how React puts resources together to build a site, including JavaScript ES6 features, CSS-in-JS approaches, and the transformation from HTML-like lines into JavaScript expressions.

To get the most out of this book

One of the goals of this book is for you to get hands-on experience using React and Hooks. Following are a couple of options that you can follow to get the most out of the content before you start.

Refresh your knowledge of React

If you haven't used React lately or are not familiar with its cutting-edge features, I recommended you jump to Chapter 10, Building a Website with React, to get an overview of the three building blocks that React relies upon to build a website: JavaScript, CSS, and HTML.

While reading the book, feel free to visit this chapter often if you run into new syntax that you are not familiar with, or you simply want to gain more insights into how each building block is utilized in React.

Use a browser without building the code

If you don't have a local environment to work with the code or you simply don't want to build the code, you can access the examples from an online server at https://codepen.io/windmaomao/pen/ExvYPEX. You should get Hello World printed on your screen in no time. Each chapter comes with a couple of playground links that you can click to follow. They appear as follows in the book:

Playground – Hello World

Feel free to play with this online example at https://codepen.io/windmaomao/pen/ExvYPEX.

Build the code yourself

If you are a hands-on person and would like to follow the code step by step in each chapter, you need to have React installed in one of your projects. Instructions to set up a React project from scratch are as follows.

npm

Visit the Node.js website, https://nodejs.org, to grab the latest versions of Node.js and npm. Pick the right version for your operating system and install it. To find out if everything has been installed properly, open a terminal, and run the following command:

node -v

If you see a version number returned by the preceding command, Node.js has been installed.

Create React App

You can get your React project up and running quickly by using the following command:

npx create-react-app my-app

Replace my-app with your desired application name. Once you have the projects ready, you can go into the my-app folder and launch it:

cd my-app

yarn start

That's it, you should see an application on your local computer. Now you can try the source code out by pasting our code over your project and compiling it locally.

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781803235950_ColorImages.pdf.

Conventions used

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

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The element can be as simple as h1, a div element, or it can be an artificial element that does things differently."

A block of code is set as follows:

fetch('/giveMeANumber').then(res => {

  ReactDOM.render(<Title />, rootEl)

})

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

let c = 3

function add(a, b) {

  console.log(a, b)

  return a + b + c

}

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "This flag can be used to decide if the UI should display the Logout or Login button."

Tips or Important Notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

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

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

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

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

Share Your Thoughts

Once you've read Designing React Hooks the Right Way, we'd love to hear your thoughts! Please click here to go straight to the Amazon review pagehttps://packt.link/r/1803235950/ for this book and share your feedback.

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