Module 4: State & Forms

Controlled Components, Validation, and Context API.

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

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)
REQ-005 To Do

Implement Authentication Flow

User Story

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.

Acceptance Criteria
  • 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 AuthContext to store user state globally.
    • Wrap the app in AuthProvider.
    • On successful login, redirect to Home and show "Welcome, [Name]" in the header.
Senior Bonus
  • Type Safety: Define AuthContextType. Do not default to null without handling it.
  • Custom Hook: Create useAuth() that throws an error if used outside the provider.
  • Persistence: Save the token to localStorage so login persists on refresh.
  • Protected Route: Create <RequireAuth> wrapper to protect the Dashboard route.
REQ-008 Form Validation with Zod

User Story: As a user, I want immediate feedback if I enter invalid data so I don't waste time submitting.

Acceptance Criteria:

  • Install zod and react-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.