Chapter 5: Must-Learn for Beginners! React Hooks and State Management (What is State?)
In the previous chapter, we deployed our website, but currently it's only for "viewing," not for "interaction." If you want to implement features like "clicking a button to increase a number" or "opening/closing a popup," you must learn React's core magic: Hooks.
In the past, front-end engineers had to slog through thick official documentation and understand the lifecycle of Class Components to master state management. But in the world of Vibe Coding, you only need to grasp the "concepts"—the complex code can be handled by AI. In this chapter, we'll explain in the simplest terms how to conquer React's two most important Hooks.
🧠 Concept Clarification: What is State?
Imagine your webpage is a "digital display board." If the board says "Current reservations: 5 people," this "5" is a State.
In traditional web development (Vanilla JS or jQuery), if you wanted to change 5 to 6, you had to manually manipulate the DOM:
- Find the
<span>tag on the page. - Erase the original number.
- Write the new number. This is like personally using a cloth and marker to update a physical board—very labor-intensive.
But in React, you just tell the system: "Add 1 to the state in my brain," and React automatically updates all parts of the interface that use this state instantly! This is called "Data-driven View."
The tool used to remember this state is called useState.
🎣 Hands-on Exercise: useState Reservation Day Calculator
Let's implement a highly common business feature: "shopping cart quantity adjustment" or "reservation day calculator."
🔥【Vibe Prompt Practical Spell】 I'm a React beginner. Please help me create a
DaysCalculator.tsxcomponent insrc/components/. Requirements:
- Use
useStateto track "reservation days (days)," with a default value of 1.- The interface should have a minus button, a text display for days, and a plus button, arranged horizontally.
- Logic constraints: Days cannot go below 1 or exceed 14 (disable and gray out the button when limits are reached).
- Dynamic pricing: Display "Total cost" below, assuming NT$ 1,200 per day, automatically multiplied and formatted with thousand separators.
- UI design: Use Tailwind CSS to create a modern Glassmorphism card style with subtle shadows.
- Add extremely detailed Chinese comments in the code to explain how
useStateworks.
The AI will generate a beautiful counter. Pay attention to this core line of code:
const [days, setDays] = useState(1);
This is React's most classic syntax—it returns an array with two things:
days: Used to read the current number of days (your variable).setDays: The remote control to change the days (a function). When the plus button is clicked, executingsetDays(days + 1)will instantly re-render the interface!
👁️ Concept Clarification: What is useEffect (Side Effects)?
Sometimes, you want "when something happens, automatically do another thing." For example:
- When the page loads, fetch the latest product data from the backend.
- When reservation days change, save this value to the browser's
localStorage. - When the user closes the window, stop the timer.
These "chain reactions" or "interactions with external systems" are called Effects in React, and we use useEffect to handle them.
🔥【Vibe Prompt Practical Spell (Continued)】 Modify the
DaysCalculator.tsxfrom earlier.
- Add
useEffect: When "reservation days (days)" changes, log "User changed days to X" in the Console (dev tools).- Add another
useEffectto show a welcome toast message when the component "first loads."- Use comments to explain to me, a beginner, what the Dependency Array means.
The AI will add this key code:
// Example 1: Dependency array has items
useEffect(() => {
console.log(`User changed days to ${days}`);
}, [days]); // <- This bracket is the Dependency Array
// Example 2: Empty dependency array
useEffect(() => {
toast.success("Welcome to the reservation system!");
}, []); // <- Empty array means "only run once on first load"
- In the first example,
daysin the brackets means: Only run the code inside whendayschanges. - The second example has an empty
[], meaning no dependencies, so it only runs once when the page loads (perfect for API calls!).
⚠️ [Common Pitfall] Infinite Loop
Beginners using useEffect often trigger "infinite loop" hell that can crash computers.
Bad Example:
const [count, setCount] = useState(0);
useEffect(() => {
setCount(count + 1); // Error! This causes an infinite loop
}, [count]);
What Happens?
- The code sees
countchange, triggeringuseEffect. useEffectexecutessetCount(count + 1).countchanges again, retriggeringuseEffect... This loops thousands of times per second until your browser crashes.
Vibe Coder Solution: If your browser freezes, it's almost always an infinite loop. Just highlight your useEffect code and ask AI: "My page froze—is this an infinite loop? Please fix the dependency array logic."
💼 [Business Applications] E-commerce "Shopping Cart" & "Recently Viewed"
Mastering useState and useEffect means you've unlocked the core money-making machine of e-commerce.
Application 1: Site-wide Shopping Cart State (with Context/Zustand)
Use state management to track items users add to their cart. When they click "Add to Cart" (setCartItems), the cart icon number updates instantly. This smooth experience boosts conversion rates.
Application 2: "Recently Viewed" Tracking
With useEffect, when a user visits a product page (component load), trigger an API to log the product ID to a "Recently Viewed" list in the database.
With this data, you can display "Recommended for You (Based on Your Recent Views)" on the homepage—a feature proven to increase average order value by at least 15%!
Next chapter, we'll combine these fundamentals to tackle web development's most complex (and lucrative) challenge: Implementing a Supabase User Login Interface!