1. Core Concepts
Controlled Inputs: In HTML, inputs manage their own state. In React, we hijack that. value={state} and onChange={setState}. The React state becomes the "single source of truth".
Context API: Solves "Prop Drilling" (passing data through 5 layers of components that don't need it).
createContext: Creates the data pipe.Provider: Puts data into the pipe at the top.useContext: Extracts data from the pipe at the bottom.
1.1 Deep Dive: Controlled vs Uncontrolled
While "Controlled" (React state drives input) is the standard, "Uncontrolled" (DOM drives input, React reads it via Ref) is valid for simple forms or integrating with non-React libraries. However, for complex validation, Controlled is king.
1.2 Industry Standard: Form Libraries
Building forms from scratch is painful. In the real world, we use libraries like React Hook Form or Formik. They handle validation, error messages, and "touched" states (knowing if a user has clicked a field) much better than manual state.
For this module, build it manually to understand the pain. In Module 5, we might use a library.
📚 Deep Dive (Documentation)
Implement Authentication Flow
As a user, I need to log in to access the dashboard. As a developer, I need a global way to check if a user is logged in.
- Login Form:
- Fields: Email, Password.
- Validation: Email must have "@", Password > 6 chars.
- Disable "Submit" button if invalid.
- Show error messages in red.
- Auth Context:
- Create
AuthContextto store user state globally. - Wrap the app in
AuthProvider. - On successful login, redirect to Home and show "Welcome, [Name]" in the header.
- Create
- Type Safety: Define
AuthContextType. Do not default tonullwithout handling it. - Custom Hook: Create
useAuth()that throws an error if used outside the provider. - Persistence: Save the token to
localStorageso login persists on refresh. - Protected Route: Create
<RequireAuth>wrapper to protect the Dashboard route.
User Story: As a user, I want immediate feedback if I enter invalid data so I don't waste time submitting.
Acceptance Criteria:
- Install
zodandreact-hook-form. - Create a schema for the Registration Form (email, password, confirm password).
- Connect the schema to the form using
zodResolver. - Display error messages below each field.