Build Robust and Scalable Forms with React Hook Form — Usman Abdur Rehman Web Forms with React
Apress Pocket Guides present concise summaries of cutting-edge developments and working practices throughout the tech industry. Shorter in length, books in this series aim to deliver quick-to-read guides that are easy to absorb, perfect for the time-poor professional. This series covers the full spectrum of topics relevant to the modern industry, from security, AI, machine learning, cloud computing, web development, product design, to programming techniques and business topics too. Typical topics might include: • A concise guide to a particular topic, method, function or framework • Professional best practices and industry trends • A snapshot of a hot or emerging topic • Industry case studies • Concise presentations of core concepts suited for students and those interested in entering the tech industry • Short reference guides outlining ‘need-to-know’ concepts and practices. More information about this series at https://link.springer.com/ bookseries/17385.
Web Forms with React Build Robust and Scalable Forms with React Hook Form Usman Abdur Rehman
Usman Abdur Rehman Islamabad, Pakistan Web Forms with React: Build Robust and Scalable Forms with React Hook Form ISBN-13 (pbk): 979-8-8688-1223-1 ISBN-13 (electronic): 979-8-8688-1224-8 https://doi.org/10.1007/979-8-8688-1224-8 Copyright © 2025 by Usman Abdur Rehman This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: James Robinson-Prior Development Editor: James Markham Editorial Assistant: Gryffin Winkler Cover designed by eStudioCalamar Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress. com/gp/services/source-code. If disposing of this product, please recycle the paper
Dedicated to my awesome mother, Waqarunnisa.
vii Table of Contents About the Author ���������������������������������������������������������������������������������xi About the Technical Reviewer �����������������������������������������������������������xiii Introduction ����������������������������������������������������������������������������������������xv Chapter 1: Forms in React ��������������������������������������������������������������������1 Native Form Handling �������������������������������������������������������������������������������������������1 Handling State �������������������������������������������������������������������������������������������������1 Handling Validation ������������������������������������������������������������������������������������������2 Standard ����������������������������������������������������������������������������������������������������������3 Learning ����������������������������������������������������������������������������������������������������������4 Scalability and Reusability ������������������������������������������������������������������������������4 Robustness ������������������������������������������������������������������������������������������������������4 The Solution ����������������������������������������������������������������������������������������������������������5 Summary���������������������������������������������������������������������������������������������������������������6 Chapter 2: React Hook Form �����������������������������������������������������������������7 Why React Hook Form? �����������������������������������������������������������������������������������������7 Performance ����������������������������������������������������������������������������������������������������8 GitHub Stats �����������������������������������������������������������������������������������������������������8 npm Installs ���������������������������������������������������������������������������������������������������10 Type Safety ����������������������������������������������������������������������������������������������������11 Zero Dependencies ����������������������������������������������������������������������������������������12 Validation �������������������������������������������������������������������������������������������������������12
viii Subscriptions �������������������������������������������������������������������������������������������������12 Cross-Platform ����������������������������������������������������������������������������������������������13 Dev Tools �������������������������������������������������������������������������������������������������������14 Form Builder ��������������������������������������������������������������������������������������������������15 Features Comparison ������������������������������������������������������������������������������������15 Summary�������������������������������������������������������������������������������������������������������������16 Chapter 3: React Hook Form Basics ���������������������������������������������������17 The Core ��������������������������������������������������������������������������������������������������������������17 Basic Usage ���������������������������������������������������������������������������������������������������18 Using TypeScript ��������������������������������������������������������������������������������������������19 useForm Returned Values �����������������������������������������������������������������������������20 useForm Params �������������������������������������������������������������������������������������������23 Summary�������������������������������������������������������������������������������������������������������������24 Chapter 4: Making Forms with React Hook Form �������������������������������25 BMI Calculator �����������������������������������������������������������������������������������������������������25 Signup Form ��������������������������������������������������������������������������������������������������������32 Integrating Controlled Components ���������������������������������������������������������������41 Summary�������������������������������������������������������������������������������������������������������������44 Chapter 5: Validation ��������������������������������������������������������������������������45 Using register Options �����������������������������������������������������������������������������������������45 register with Validation and Error Message ��������������������������������������������������������46 register with the validate Function ���������������������������������������������������������������������48 Validation Options �����������������������������������������������������������������������������������������������51 mode/reValidateMode �����������������������������������������������������������������������������������51 criteriaMode ��������������������������������������������������������������������������������������������������53 shouldFocusError ������������������������������������������������������������������������������������������55 delayError ������������������������������������������������������������������������������������������������������55 Table of ConTenTs
ix Validation Using Schema ������������������������������������������������������������������������������������55 Schema Validation Using Yup ������������������������������������������������������������������������56 Schema Validation Using Zod ������������������������������������������������������������������������58 Summary�������������������������������������������������������������������������������������������������������������59 Chapter 6: Common Use Cases �����������������������������������������������������������61 Deeply Nested Form ��������������������������������������������������������������������������������������������63 Dependent Fields ������������������������������������������������������������������������������������������������65 Reusable Fields ���������������������������������������������������������������������������������������������������68 Reusable Controlled Components �����������������������������������������������������������������������72 Mapping Multiple Fields ��������������������������������������������������������������������������������������75 Summary�������������������������������������������������������������������������������������������������������������78 Index ���������������������������������������������������������������������������������������������������79 Table of ConTenTs
xi About the Author Usman Abdur Rehman is a frontend tech lead for a US-based healthcare company with over four years of professional experience. As a self-taught developer, Usman studied everything related to programming from YouTube videos, tutorials, blogs, and books. Since gaining his first developer role, Usman has been motivated to give back to the community by teaching coding.
xiii About the Technical Reviewer Alexandru Tepes is a full-time software engineer with a love for technology and health. He enjoys sharing what he's learned, reaching over 50,000 views on Medium with his simple and practical insights. Passionate about making complex ideas easy to understand, Alexandru writes about software, healthy living, and the ways these worlds connect. His goal is to help and inspire others to grow, learn, and improve their lives. When not working on software or writing, Alex explores how technology can enhance everyday experiences. This book is part of his journey to share knowledge and make a positive impact.
xv Introduction Web Forms with React is a succinct and practical guide to building robust, scalable, and reusable forms in React. Forms are an integral part of any software and are the source of data we see entered on the Web. From social media posts to selling products on ecommerce sites to YouTube videos and blog posts, most of the information on the Web is present because of the data that was entered through forms. It is therefore vital that we know how to properly handle forms, how to properly scale them, how to handle validations, etc. This book is a one-stop guide to setting up web forms from scratch using one of the most popular and robust frontend frameworks in use today, React Hook Form. Standards and best practices are vital for everything we do, and a proper standard should be set in place so that everyone does the same thing and everyone is aware of the pros/cons of whatever might occur while adopting that practice. Forms in React can be handled in a hundred different ways, and this book proposes to set the standard on how to handle and set up forms using React. Once standards are in place, developers will be able to code robust, bug-free forms because they know they are making forms that are being used by millions of developers and if they run into issues they would be able to find solutions to those issues pretty easily. It is also important that scalability is kept in mind while making any software feature, whether it’s a server function, a UI component, or something else. React Hook Form makes sure that the forms are not only performant but also scalable. Most of the time, a certain part of a form gets repeated across an application. For example, the email and password fields are often present in the Signin, Signup, and Edit Profile sections, and they
xvi have a similar set of validations, constraints, etc. So we will look at how to handle these so they can be reused across the application where they are required. Validations are always important whether they are server-side or client-side validations. React Hook Form provides a nice interface for hooking up validations by either using normal HTML validation or using a third-party validation library like Yup, Zod, etc. By the end of this book, you will have the knowledge and confidence to build strong and reusable web forms from the ground up. InTroduCTIon
1© Usman Abdur Rehman 2025 U. A. Rehman, Web Forms with React, Apress Pocket Guides, https://doi.org/10.1007/979-8-8688-1224-8_1 CHAPTER 1 Forms in React Forms are an integral part of any software including the Web and are the way of data entry for all the user data you see on the Web. From social media posts to ecommerce products to YouTube videos/blog posts, most data on the Web is present because of the data that was entered through forms. It is therefore vital that you know how to properly handle forms, how to properly scale them, how to handle validations for them, etc. This chapter talks about the usual approach taken by novice developers for handling forms in React and the cons of it. Native Form Handling Working with forms requires a lot of different steps from handling state to validation to making sure the form is robust, scalable, and reusable. I would go through every step to see how native React handles all these and what are the cons related to them. Handling State Listing 1-1 shows you what a traditional form looks like with native state handling (using useState).
2 Listing 1-1. The traditional way of handling state import { useState } from "react"; export const HandlingState = () => { const [name, setName] = useState(""); return ( <form> <input value={name} onChange={(e) => setName(e.target. value)} /> </form> ); }; What should you do in the case when there are multiple fields in a form? Should you use two states for those two fields or one object state that handles the state for the whole form? There is no standard for it. Also, this traditional way of performing state update triggers rerenders on every keystroke and can be disastrous if you have a large form that hasn’t been memoized properly. Handling Validation Listing 1-2 shows you how traditional validation is performed in forms. Listing 1-2. The traditional way of handling validation import { useState } from "react"; export const HandlingValidation = () => { const [name, setName] = useState(""); const [error, setError] = useState(""); return ( <form> <input Chapter 1 Forms in reaCt
3 value={name} onChange={(e) => setName(e.target.value)} onBlur={(e) => { if (!e.target.value) setError("The name is required"); else setError(""); }} /> {error && <p>{error}</p>} </form> ); }; Again, there is no standard for validating forms natively. Maybe there is a requirement for handling validations on change, focus, or form submission; the way the validation is applied could differ depending on which scenario it is. Also let’s say you want to apply a complex validation use case where you want that if a field is visited (touched) and the validation fails on change, then the related validation error should be shown. The inclusion of more states and conditions for handling cases like these could introduce bugs in the form. There is a need for a clear-cut standard for doing validations. Standard As discussed in the previous two sections, there is no standard for performing validations, handling state, or making a form in React. When that is the case, there is a high chance every developer on your team would use a different strategy to make forms. Since everything can be done in a million different ways, every person on the team would use their strategy to implement a certain feature, which, when the feature would be worked Chapter 1 Forms in reaCt
4 on again in the future, to fix a bug or to add an enhancement, would not present an ideal solution since not everyone is familiar with that strategy the developer used to code the feature. Learning Even if you have a particular custom form-making strategy/standard in your company, if you get stuck somewhere, the only way to get through that is to consult your team members. There would be no resources on the Internet regarding learning it or fixing bugs if you ever encounter one. Scalability and Reusability If you make a form using native state handling and custom validation logic, it will not scale properly. The first reason for that is performance. If you make a form in React using no widely used/accepted standard, there is a chance it has some performance flaws in it, which would hurt you in the longer run once you start using these methodologies to make bigger forms. The second reason for that is reusability. You would be able to scale better if you could make easy-to-use, reusable form components out of an existing form. The crux of React or any other modern framework is reusability, and if you can’t do that, then any development approach would not work. Robustness Each and every part of your web application must be robust and not error- prone. Using a nonstandard way of making forms won’t help achieve that objective. Chapter 1 Forms in reaCt
5 The Solution The solution for every con that we face as described above is using a library that is used by millions of developers around the world. Using a library gives us the following advantages: 1. You would have a standard for building forms, and that standard would be easily adaptable and learnable by developers who would be joining your team. Following a standard would ensure there would be a certain set of practices that would be used by developers in your team so the chances of something going wrong would be minimal as well. 2. This would ensure that the application you are building is robust since a library with millions of downloads, hundreds of issue resolutions, etc. is ideally bug-free and has been through the rigorous cycle of development that every software practice goes through. 3. Scalability/reusability would be available out of the box since it would ensure that you are using one of the best strategies, if not the best strategy, for building forms both performance- and coding-wise. 4. It would have a developer-friendly API so you will be able to solve complex issues while using minimal code and would be able to focus on building vital features of your application without worrying about the standard, robustness, etc. of your form code. Chapter 1 Forms in reaCt
6 Summary In this chapter we discussed the current form-making strategies in React in detail and why it is not recommended to make forms that way. In the next chapter, we will take a look at a very popular and widely used React form library, React Hook Form, and we will see how it addresses all our concerns that we discussed in this chapter. Chapter 1 Forms in reaCt
7© Usman Abdur Rehman 2025 U. A. Rehman, Web Forms with React, Apress Pocket Guides, https://doi.org/10.1007/979-8-8688-1224-8_2 CHAPTER 2 React Hook Form In the last chapter, we looked at the cons of using our custom approaches to manage form actions like state management, validations, etc. We saw how using traditional ways of building forms can make our forms less robust and scalable and how not following a standard brings nonuniformity to your application. In this chapter, we will discuss React Hook Form, a library that is being used by millions of developers to make performant and robust forms. We will take a look at why I chose this library and what it brings to the table. Why React Hook Form? While searching for that one React form library, I stumbled upon a lot of different options, some of which I had used in a professional capacity before as well. React Hook Form checked a lot of boxes and was so far the best choice compared with the other options like Formik, Redux Form, etc. In this section, we will take a look at why you as a React developer should consider building your forms using this library and how React Hook Form is comparatively better than other React form libraries like Formik and Redux Form.
Comments 0
Loading comments...
Reply to Comment
Edit Comment