29,99 €
Maximilian Schwarzmüller is a bestselling instructor who has helped more than three million students worldwide learn how to code. His bestselling React video course, “React – The Complete Guide”, has over nine hundred thousand students on Udemy.
Max has written this quick-start reference that distills the core concepts of React. Simple explanations, relevant examples, and step-by-step derivations make this guide the ideal resource for busy developers. In this second edition, Max guides you through changes brought by React 19, including the new use() hook, form actions, and how to think about React on the server.
This book will support you through your next React projects in giving you a behind-the-scenes understanding of the framework – whether you've just finished Max's video course and are looking for a handy reference, or you’re using a variety of other learning materials and need a single study guide to bring everything together.
You’ll find full solutions to all end-of-chapter quizzes and exercises in the book’s GitHub repository.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 738
Veröffentlichungsjahr: 2025
React Key Concepts
Second Edition
An in-depth guide to React’s core features
Maximilian Schwarzmüller
React Key Concepts
Second Edition
Copyright © 2024 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.
Publishing Product Manager: Lucy Wan
Acquisition Editor – Peer Reviews: Jane Dsouza
Project Editor: Janice Gonsalves
Senior Development Editor: Elliot Dallow
Copy Editor: Safis Editing
Technical Editor: Tejas Mhasvekar
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Presentation Designer: Ajay Patule
Developer Relations Marketing Executive: Priyadarshini Sharma
First published: December 2022
Second edition: December 2024
Production reference: 1231224
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-83620-227-1
www.packt.com
Maximilian Schwarzmüller is a professional web developer and bestselling online course instructor. On Udemy, he is one of the most popular and biggest online instructors, teaching more than 3 million students worldwide. Students can become developers by exploring his more than 40 courses, most of them bestsellers in their respective categories.
Besides helping students from all over the world, Maximilian loves exploring and mastering new technologies, building exciting digital products, and sharing his knowledge with fellow developers. He’s driven by his passion for good code and engaging websites and apps.
I may be the author of this book but planning, polishing, and publishing this book was really a group effort.
Most of all, I’m thankful for all the support from my wife Anna-Maria. You’re the love of my life!
I also want to thank my publisher, Packt: Thank you Bridget, Megan, Elliot, Janice, Lucy, Tejas, and everyone else who was involved!
Cihan Yakar has over twenty years of experience in software development. He specializes in fullstack development and machine learning, creating applications with .NET and Node.js. An enthusiastic learner and knowledge sharer, Cihan often speaks at user group meetings. He is the founder of Bitsody Software and Defne Software. He was also a technical reviewer of The TypeScript Workshop. To discover more about his professional journey, feel free to connect with him on LinkedIn. When not working, Cihan enjoys spending time with his family and indulging in his passion for all things Star Trek.
Slava Knyazev has been writing software since his early teenage years and is always seeking to find ways to improve his mastery of the craft. He has worked for well-known names, including theScore, Amazon Web Services, and Airbnb. When he isn’t writing code, he dives into technical topics on his blog, Building Better Software Slower.
Eric Harvey is a consultant for Enwise Webtech LLC, focused on EdTech and secure systems integrations. He has worked in technology since 1998, his roles have included: applications engineer, web developer, manager of learning systems at a major university, and solutions engineer. In 2005, he founded a web development and hosting services company. Outside of work he is an avid collector of board games and vintage computers, and plays mandolin in a local Celtic string band.
I would like to thank my kids – Amber, Nate, and Rylan – and my wife, Meredith, for being understanding, patient, and always loving.
Read this book alongside other users, AI experts, and the author himself.
Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more.
Scan the QR code or visit the link to join the community.
https://packt.link/ReactKeyConcepts2e
Contributors
About the Author
About the Reviewers
Join Us on Discord
Preface
Who This Book Is For
What This Book Covers
Staying Up to Date with This Book
Following Along with the Book
Installing React.js
Download the Example Code Files
Download the Color Images
Conventions Used
Get in Touch
Share Your Thoughts
Download the Free PDF and Supplementary Content
Description of Supplementary Content
React – What and Why
Introduction
What is React?
The Problem with “Vanilla JavaScript”
React and Declarative Code
How React Manipulates the DOM
Introducing SPAs
Creating a React Project with Vite
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Join Us on Discord
Understanding React Components and JSX
Introduction
What Are Components?
Why Components?
The Anatomy of a Component
What Exactly Are Component Functions?
What Does React Do with All These Components?
Built-In Components
Naming Conventions
JSX vs HTML vs Vanilla JavaScript
Using React without JSX
JSX Elements Are Treated Like Regular JavaScript Values
JSX Elements Must Have a Closing Tag
Moving Beyond Static Content
Outputting Dynamic Content
Rendering Images
When Should You Split Components?
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 2.1: Creating a React App to Present Yourself
Activity 2.2: Creating a React App to Log Your Goals for This Book
Components and Props
Introduction
Can Components Do More?
Using Props in Components
Passing Props to Components
Consuming Props in a Component
Components, Props, and Reusability
The Special “children” Prop
Which Components Need Props?
How to Deal with Multiple Props
Spreading Props
Prop Chains/Prop Drilling
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 3.1: Creating an App to Output Your Goals for This Book
Working with Events and State
Introduction
What’s the Problem?
How Not to Solve the Problem
A Better Incorrect Solution
Improving the Solution by Properly Reacting to Events
Updating State Correctly
A Closer Look at useState()
A Look Under the Hood of React
Working with Multiple State Values
Using Multiple State Slices
Managing Merged State Objects
Updating State Based on Previous State Correctly
Two-Way Binding
Deriving Values from State
Working with Forms and Form Submission
Lifting State Up
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 4.1: Building a Simple Calculator
Activity 4.2: Enhancing the Calculator
Rendering Lists and Conditional Content
Introduction
What Are Conditional Content and List Data?
Rendering Content Conditionally
Different Ways of Rendering Content Conditionally
Utilizing Ternary Expressions
Abusing JavaScript Logical Operators
Get Creative!
Which Approach is Best?
Setting Element Tags Conditionally
Outputting List Data
Mapping List Data
Updating Lists
A Problem with List Items
Keys to the Rescue!
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 5.1: Showing a Conditional Error Message
Activity 5.2: Outputting a List of Products
Styling React Apps
Introduction
How Does Styling Work in React Apps?
Using Inline Styles
Setting Styles via CSS Classes
Setting Styles Dynamically
Conditional Styles
Combining Multiple Dynamic CSS Classes
Merging Multiple Inline Style Objects
Building Components with Customizable Styles
Customization with Fixed Configuration Options
The Problem with Unscoped Styles
Scoped Styles with CSS Modules
The styled-components Library
Use the Tailwind CSS Library for Styling
Using Other CSS or JavaScript Styling Libraries and Frameworks
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 6.1: Providing Input Validity Feedback upon Form Submission
Activity 6.2: Using CSS Modules for Style Scoping
Portals and Refs
Introduction
A World without Refs
Refs versus State
Using Refs for More than DOM Access
Refs in Custom Components
Controlled versus Uncontrolled Components
React and Where Things End up in the DOM
Portals to the Rescue
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Have Learned
Activity 7.1: Extract User Input Values
Activity 7.2: Add a Side Drawer
Handling Side Effects
Introduction
What’s the Problem?
Understanding Side Effects
Side Effects Are Not Just about HTTP Requests
Dealing with Side Effects with the useEffect() Hook
How to Use useEffect()
Effects and Their Dependencies
Unnecessary Dependencies
Cleaning Up after Effects
Dealing with Multiple Effects
Functions as Dependencies
Avoiding Unnecessary Effect Executions
Effects and Asynchronous Code
Rules of Hooks
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 8.1: Building a Basic Blog
Handling User Input & Forms with Form Actions
Introduction
Handling Form Submissions without Actions
Extracting User Input
Tracking State
Relying on Refs
Taking Advantage of the event Object
Which Solution Is Best?
Handling Form Submissions with Actions
Synchronous vs Asynchronous Actions
Behind the Scenes: Actions Are Transitions
Managing State Based on Form Submissions
Updating UI State with useActionState()
Managing Pending UI State with useActionState()
Handling Pending UI State with useFormStatus()
Performing Optimistic Updates
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 9.1: Managing a Feedback Form
Behind the Scenes of React and Optimization Opportunities
Introduction
Revisiting Component Evaluations and Updates
What Happens When a Component Function Is Called
The Virtual DOM vs the Real DOM
State Batching
Avoiding Unnecessary Child Component Evaluations
Avoiding Costly Computations
Utilizing useCallback()
Using the React Compiler
Avoiding Unnecessary Code Download
Reducing Bundle Sizes via Code Splitting (Lazy Loading)
Strict Mode
Debugging Code and the React Developer Tools
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 10.1: Optimize an Existing App
Working with Complex State
Introduction
A Problem with Cross-Component State
Using Context to Handle Multi-Component State
Providing and Managing Context Values
Using Context in Nested Components
Changing Context from Nested Components
Using the Context API Efficiently
Getting Better Code Completion
Context or Lifting State Up?
Outsourcing Context Logic into Separate Components
Combining Multiple Contexts
Limitations of useState( )
Managing State with useReducer( )
Understanding Reducer Functions
Dispatching Actions
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 11.1: Migrating an App to the Context API
Activity 11.2: Replacing useState() with useReducer()
Building Custom React Hooks
Introduction
Introducing Custom Hooks
Why Would You Build Custom Hooks?
A First Custom Hook
Custom Hooks: A Flexible Feature
Custom Hooks and Parameters
Custom Hooks and Return Values
A More Complex Example
Building a First Version of the Custom Hook
Making the Hook Useful by Returning Values
Improving Reusability by Accepting an Input Parameter
Using Custom Hooks for Context Access
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 12.1: Build a Custom Keyboard Input Hook
Multipage Apps with React Router
Introduction
One Page Is Not Enough
Getting Started with React Router and Defining Routes
Adding Page Navigation
Working with Layouts & Nested Routes
From Link to NavLink
Route Components versus “Normal” Components
From Static to Dynamic Routes
Extracting Route Parameters
Creating Dynamic Links
Navigating Programmatically
Redirecting
Handling Undefined Routes
Lazy Loading
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 13.1: Creating a Basic Three-Page Website
Managing Data with React Router
Introduction
Data Fetching and Routing Are Tightly Coupled
Sending HTTP Requests without React Router
Loading Data with React Router
Getting Access to Loaded Data
Loading Data for Dynamic Routes
Loaders, Requests, and Client-Side Code
Layouts Revisited
Reusing Data across Routes
Handling Errors
Onward to Data Submission
Working with action() and Form Data
Returning Data Instead of Redirecting
Controlling Which <Form> Triggers Which Action
Reflecting the Current Navigation Status
Submitting Forms Programmatically
Behind-the-Scenes Data Fetching and Submission
Deferring Data Loading
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 14.1: A To-Dos App
Server-side Rendering & Building Fullstack Apps with Next.js
Introduction
What’s the Problem with Client-Side React Apps?
Making Sense of Server-side Rendering (SSR)
Adding SSR to a React Application
Server-side Data Fetching Is Not Trivial
Introducing Next.js
Creating Next.js Projects
Working with File-Based Routes
Server-side Rendering with Next.js
Working with Layouts
Managing Internal Navigation
Highlighting Active Links & Using the “use client” Directive
Creating & Using Regular Components
Handling Dynamic Routes
Other Filename Conventions
Diving Deeper into Next.js
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 15.1: Migrating a Vite-Based React Router App
React Server Components & Server Actions
Introduction
The Problem with Server-side Data Fetching
Introducing RSCs
Making Sense of RSCs
Creating & Using RSCs
Unlocking RSCs in React Projects
RSCs and Server Actions Can’t Be Used in All Projects
RSCs vs Server-side Rendering
RSCs vs Client Components
Not All Components Should Be RSCs
‘use client’ Affects Child Components, Too!
Combining RSCs and Client Components
Advanced Data Fetching with Next.js
Managing Loading States with Next.js
From Data Fetching to Data Mutations
Handling Data Mutations with Server Actions
Unlocking Server Actions in React Projects
Defining and Triggering Server Actions
Handling User Input & Updating the UI
Server Actions and useActionState()
Storing Server Actions in Separate Files
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 16.1: Build a Mini Blog
Understanding React Suspense & The use() Hook
Introduction
Showing Granular Fallback Content with Suspense
Using Suspense for Data Fetching with Next.js
Using Suspense in Other React Projects—Possible, But Tricky
Suspense Does Not Work with useEffect()
Fetching Data while Rendering—the Incorrect Way
Getting Suspense Support Is Tricky
Using Suspense for Data Fetching with Supporting Libraries
use()ing Data while Rendering
Suspense Usage Patterns
Revealing Content Together
Revealing Content as Soon as Possible
Nesting Suspended Content
Should You Fetch Data via Suspense or useEffect()?
Summary and Key Takeaways
What’s Next?
Test Your Knowledge!
Apply What You Learned
Activity 17.1: Implement Suspense in the Mini Blog
Next Steps and Further Resources
Introduction
How Should You Proceed?
Become a Fullstack React Developer
Interesting Problems to Explore
Build a Shopping Cart
Build an Application’s Authentication System (User Signup and Login)
Build an Event Management Website
Common and Popular React Libraries
Using TypeScript
Other Resources
Beyond React for Web Applications
Final Words
Join Us on Discord
Why Subscribe?
Other Books You May Enjoy
Share Your Thoughts
Index
Download the Free PDF and Supplementary Content
Description of Supplementary Content
Cover
Index
Once you’ve read React Key Concepts, Second Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page 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.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
Additionally, with this book you get access to supplementary/bonus content for you to learn more. You can use this to add on to your learning journey on top of what you have in the book.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily.
Follow these simple steps to get the benefits:
Scan the QR code or visit the link below:https://packt.link/supplementary-content-9781836202271
Submit your proof of purchase.Submit your book code. You can find the code on page no. 169 of the book.That’s it! We’ll send your free PDF, supplementary content, and other benefits to your email directlyThis book comes with the following bonus material (claimable via the mechanism described above):
A cheatsheet accompanying every chapter of the bookA video in which author Maximilian gives you his recommendations for next steps after finishing this bookA video in which author Maximilian shares his thoughts about the future of React