> For the complete documentation index, see [llms.txt](https://personal-space-4.gitbook.io/complete-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://personal-space-4.gitbook.io/complete-guide/instructor_notes_gitbook.md). Agents can also search and read this documentation through its [MCP server](https://personal-space-4.gitbook.io/complete-guide/~gitbook/mcp).

# INSTRUCTOR\_NOTES\_GITBOOK

{% hint style="danger" %}
**CONFIDENTIAL - DO NOT SHARE WITH STUDENTS**

This is the complete step-by-step guide with debugging checkpoints, theory references, and flow management.
{% endhint %}

***

## Quick Navigation

* [Pre-Workshop Setup](#pre-workshop-setup)
* [Workshop Coverage Checklist](#workshop-coverage-checklist)
* [Detailed Live Coding Script](#detailed-live-coding-script)
  * [PEMBUKAAN](#pembukaan-5-minutes)
  * [STEP 1: useState](#step-1-usestate---state-management-15-minutes)
  * [STEP 2: Event Handlers & Async Operations](#step-2-event-handlers--async-operations-15-minutes)
  * [STEP 3: Error Handling](#step-3-error-handling-8-minutes)
  * [STEP 4: useEffect](#step-4-useeffect---side-effects-12-minutes)
  * [STEP 5: useRef](#step-5-useref---dom-references-10-minutes)
  * [STEP 6: Custom Hook Refactoring](#step-6-custom-hook-refactoring-20-minutes)
* [BONUS TOPICS](#bonus-topics)
* [TIME MANAGEMENT & FLEXIBILITY GUIDE](#time-management--flexibility-guide)
* [FINAL NOTES FOR INSTRUCTOR](#final-notes-for-instructor)
* Referensi teori: [THEORY](https://personal-space-4.gitbook.io/complete-guide/theory.md)

***

## Pre-Workshop Setup

### 30 Minutes Before Workshop

* Test all code in fresh environment
* Prepare timer (visible to you)
* Open THEORY.md in separate tab for reference
* Have Chat.solution.jsx ready as backup
* Test screen sharing and audio
* Prepare whiteboard/drawing tool for diagrams

### What to Have Open

* VS Code with Chat.jsx
* Browser with localhost:5173
* Console (for debugging)
* This instructor notes
* THEORY.md for quick reference

***

## Workshop Coverage Checklist

### Core Concepts (Must Cover)

* useState for state management
* Immutable state updates
* Functional state updates
* Async operations with state
* Error handling with state
* useEffect for side effects
* Dependencies array
* useRef for DOM references
* Custom hooks for code organization

### Debugging Checkpoints (Must Show)

* Console.log to track renders
* Console.log to check state values
* React DevTools to inspect state
* Network tab (bonus for API)
* Show errors intentionally

### Theory References (Must Mention)

* Point to THEORY.md for deep dives
* Explain "why" not just "how"
* Compare patterns (good vs bad)
* Show real-world analogies

***

## DETAILED LIVE CODING SCRIPT

### PEMBUKAAN (5 minutes)

#### \[00:00 - 00:02] Welcome & Context

**Script:**

{% hint style="info" %}
"Selamat datang di workshop React Hooks! Hari ini kita akan belajar **kapan**, **kenapa**, dan **bagaimana** menggunakan hooks melalui case study yang praktis: Chatbot UI.

Kenapa chatbot? Karena chatbot adalah perfect example untuk hooks:

* State yang berubah (messages, loading, error)
* Async operations (bot response)
* Side effects (auto-scroll)
* Complex logic yang perlu clean architecture

Tujuan kita: **Understanding over syntax**. Bukan cuma bikin chatbot jalan, tapi paham reasoning di balik setiap keputusan."
{% endhint %}

**Checklist:**

* Students tau tujuan workshop
* Students paham kenapa case study ini dipilih

***

#### \[00:02 - 00:03] Show Project Structure

**Terminal:**

```bash
cd case-study-chatbot-ai
npm run dev
```

**Browser:** Navigate to `http://localhost:5173`

**Show to students:**

1. UI sudah complete (ChatShell, input, messages)
2. 3 static messages tampil
3. Input tidak berfungsi (expected!)
4. Clear button tidak berfungsi (expected!)

**Explain:**

{% hint style="success" %}
"UI components sudah jadi lengkap - ChatShell untuk container, ChatComposer untuk input, MessageBubble untuk display. Ini semua pure presentation components.

Fokus kita: **Chat.jsx** - di sinilah magic happens. Di sinilah kita implement hooks step by step."
{% endhint %}

***

#### \[00:03 - 00:05] Project Tour

**Open in VS Code:**

```
src/
├── components/
│   ├── Chat.jsx          ← FOKUS KITA
│   ├── ChatShell.jsx     ← Complete (UI only)
│   ├── ChatComposer.jsx  ← Complete (UI + local state)
│   └── MessageBubble.jsx ← Complete (UI only)
├── App.jsx               ← Minimal (hanya import Chat)
└── main.jsx
```

**Open Chat.jsx:**

**Point out structure:**

{% hint style="info" %}
"Lihat file Chat.jsx. Ada 3 bagian besar:

1. **Mock data** di atas (untuk starting point)
2. **TODOs dengan komentar lengkap** - ini roadmap kita
3. **JSX return** di bawah - sudah jadi

Strategi: kita implement TODOs satu per satu, test setelah setiap step, dan **understand WHY** sebelum move on."
{% endhint %}

**Checklist Pembukaan:**

* All students dapat buka project di browser
* All students dapat buka Chat.jsx di editor
* Students paham file structure
* Students tau file mana yang akan di-edit

***

### STEP 1: useState - State Management (15 minutes)

#### \[PHASE 1: Theory - 3 minutes]

**THEORY REFERENCE:** Open `THEORY.md` and point to "useState - State Management" section

**Talking Points:**

#### 1. What is State? (1 min)

**Diagram: Component Render Cycle**

```mermaid
graph TD
    A[Initial Render] --> B[State Created]
    B --> C[JSX Returned]
    C --> D[DOM Updated]
    D --> E[User Interaction]
    E --> F[setState Called]
    F --> G[State Updated]
    G --> H[Re-Render]
    H --> I[JSX Returned]
    I --> J[DOM Updated]
    J --> E
```

{% hint style="info" %}
**Alternative: ASCII Diagram**

```
Component Render Cycle:

    Initial Render
          ↓
    [State Created]
          ↓
      JSX Returned
          ↓
    DOM Updated
          ↓
   User Interaction
          ↓
    setState Called
          ↓
    [State Updated] ──→ Re-Render ──→ JSX Returned ──→ DOM Updated
          ↑                                                 │
          └─────────────────────────────────────────────────┘
```

{% endhint %}

**Explain:**

{% hint style="info" %}
"State adalah 'memory' component yang:

1. **Persist across renders** - tidak hilang setiap render
2. **Trigger re-render** - perubahan state = UI update
3. **Isolated per component** - setiap instance punya state sendiri

Bedanya dengan variable biasa?"
{% endhint %}

**Demo comparison:**

```javascript
// ❌ Variable biasa
let count = 0;
count = count + 1;  // Berubah di memory
// ❌ UI tidak update! React tidak tahu ada perubahan.

// ✅ State
const [count, setCount] = useState(0);
setCount(count + 1);  // Berubah + trigger re-render
// ✅ UI update otomatis! React track state changes.
```

**Key point:**

{% hint style="warning" %}
"React tidak 'watch' variables. React hanya re-render saat state/props berubah."
{% endhint %}

***

#### 2. When to Use useState? (1 min)

**Decision Tree: When to Use useState**

```
Apakah data ini perlu ditampilkan di UI?
├─ Yes: Apakah data berubah?
│  ├─ Yes → useState ✅
│  └─ No → const variable
└─ No: Apakah perlu persist?
   ├─ Yes → useRef
   └─ No → const variable
```

**Examples:**

| Use Case          | useState? | Why                           |
| ----------------- | --------- | ----------------------------- |
| Form input value  | Yes       | UI shows value, value changes |
| Modal open/closed | Yes       | UI responds to toggle         |
| API response      | Yes       | UI shows data after load      |
| Timer ID          | No        | Internal value, no UI         |
| DOM ref           | No        | Use useRef instead            |
| Constant config   | No        | Never changes                 |

***

#### 3. useState Syntax (1 min)

**Syntax Breakdown:**

```javascript
const [currentValue, setterFunction] = useState(initialValue);
//      ↑              ↑                         ↑
//   read-only      updater              used once on mount
```

**Explain each part:**

{% hint style="success" %}
`currentValue` - The state value. **Read-only!** Never mutate directly.

`setterFunction` - Function untuk update state. Convention: `set[StateName]`.

`initialValue` - Value saat first render. **Only used once!** Di render berikutnya, React sudah punya state stored.

**Destructuring:** useState return array, bukan object. Kenapa? Flexible naming. Bisa `[count, setCount]` atau `[num, setNum]` terserah kita.
{% endhint %}

**Analogy:**

{% hint style="info" %}
"Bayangkan state seperti kotak penyimpanan:

* `currentValue` = lihat isi kotak (read-only)
* `setterFunction` = masukkan item baru (React tutup kotak lama, buka kotak baru)
* `initialValue` = isi awal kotak saat pertama kali dibuat"
  {% endhint %}

**Checklist Theory:**

* Students paham state vs variable
* Students paham state trigger re-render
* Students paham sintaks destructuring
* Students paham initial value concept

***

#### \[PHASE 2: Live Coding - 8 minutes]

**Goal:** Declare 3 state variables (messages, status, error)

**Code Location:** `src/components/Chat.jsx`

***

**Step 1.1: Import useState (1 min)**

**Find line 1:**

```javascript
import ChatShell from "./ChatShell";
```

**Type slowly (explain as you type):**

```javascript
import { useState } from "react";  // ← ADD THIS
import ChatShell from "./ChatShell";
```

**Explain:**

{% hint style="info" %}
"useState adalah named export dari React. Bukan default export, jadi pakai curly braces."
{% endhint %}

***

**Step 1.2: Add Render Tracker (1 min)**

**Find line \~20 (start of Chat function):**

```javascript
export default function Chat() {
  // ADD THIS for debugging
  console.log("🔄 RENDER: Chat component rendered");
  
  // ... rest of code
}
```

**Explain:**

{% hint style="info" %}
"Debugging tip: tambahkan console.log untuk track renders. Setiap kali component render, log ini muncul. Nanti kita akan lihat log ini muncul lagi setiap kali state berubah - ini bukti re-render!"
{% endhint %}

**DEBUG CHECKPOINT 1:**

**Action:**

1. Save file (Cmd/Ctrl + S)
2. Check browser console
3. Point out log muncul sekali

**Show to students:**

{% hint style="success" %}
"Lihat console: log muncul 1x. Component rendered saat mount. Tunggu sampai kita update state nanti - log akan muncul lagi!"
{% endhint %}

***

**Step 1.3: Declare Messages State (2 min)**

**Find comment (\~line 30):**

```javascript
// TODO: Tambahkan useState untuk messages
```

**DELETE placeholder and TYPE:**

```javascript
// State untuk menyimpan messages
const [messages, setMessages] = useState(mockMessages);
console.log("📦 Messages state:", messages);
```

**Explain while typing:**

{% hint style="info" %}
"Let's break this down:

**`messages`** = Current state. Array of message objects. **Read-only!**

**`setMessages`** = Updater function. Satu-satunya cara untuk update messages state.

**`useState(mockMessages)`** = Initial value. mockMessages adalah array dengan 3 messages. Ini value untuk first render. Di render berikutnya, React ingat value terakhir yang kita set.

**Console.log** = Debug tool. Kita log state untuk verify isinya."
{% endhint %}

**DEBUG CHECKPOINT 2:**

**Action:**

1. Save file
2. Check browser console
3. Expand logged array

**Point out:**

```
🔄 RENDER: Chat component rendered
📦 Messages state: (3) [{…}, {…}, {…}]
  0: {id: 'm1', role: 'model', content: 'Halo! Aku chatbot 🙂'}
  1: {id: 'm2', role: 'user', content: 'Nanti kita fokus ke hooks ya?'}
  2: {id: 'm3', role: 'model', content: 'Yes. Mulai dari...'}
```

**Explain:**

{% hint style="success" %}
"Perfect! State initialized dengan 3 messages. Ini proof state kita punya data yang benar."
{% endhint %}

***

**Step 1.4: Declare Status State (2 min)**

**Find next TODO:**

```javascript
// TODO: Tambahkan useState untuk status
```

**DELETE placeholder and TYPE:**

```javascript
// State untuk track async process status
const [status, setStatus] = useState('idle');
console.log("🚦 Status state:", status);
```

**Explain:**

{% hint style="info" %}
"Status state untuk track apakah sedang ada proses async.

**3 possible values:**

* `'idle'` = tidak ada proses (default)
* `'loading'` = sedang proses (akan kita set saat bot thinking)
* `'error'` = ada error

Ini yang disebut **State Machine Pattern**. Status cuma bisa salah satu dari 3 states ini. Tidak ada grey area."
{% endhint %}

**Diagram: State Machine Flow**

```
        User sends message
              ↓
     ┌───────────────┐
     │     IDLE      │ ← Default
     └───┬───────┬───┘
         │       ↑
    send │       │ success/error
         ↓       │
     ┌───────────┴───┐
     │   LOADING     │
     └───────────────┘
         │
         ↓ (if error)
     ┌───────────────┐
     │    ERROR      │
     └───────────────┘
```

**Explain:**

{% hint style="success" %}
"Setiap async operation follow flow ini. UI bisa respond based on status:

* idle → show normal UI
* loading → show spinner
* error → show error message"
  {% endhint %}

***

**Step 1.5: Declare Error State (1 min)**

**Find next TODO and TYPE:**

```javascript
// State untuk menyimpan error message
const [error, setError] = useState(null);
console.log("⚠️ Error state:", error);
```

**Explain:**

{% hint style="info" %}
"Error state untuk simpan error message.

**2 possible values:**

* `null` = no error (default)
* `string` = error message

**Why error needs to be state?** Karena kita perlu **tampilkan** error ke user di UI. Error bukan cuma console.log yang cuma developer lihat!"
{% endhint %}

**DEBUG CHECKPOINT 3:**

**Action:**

1. Save file
2. Check console logs

**Show:**

```
🔄 RENDER: Chat component rendered
📦 Messages state: (3) [{…}, {…}, {…}]
🚦 Status state: idle
⚠️ Error state: null
```

**Explain:**

{% hint style="success" %}
"All 3 states initialized correctly. Status = idle (no process), Error = null (no error)."
{% endhint %}

***

**Step 1.6: Remove OLD Placeholders (1 min)**

**Find and DELETE these lines (\~line 50):**

```javascript
// DELETE THESE:
const status = "idle";
const error = null;
```

**Explain:**

{% hint style="warning" %}
"These were placeholders. Sekarang kita sudah punya real state, delete placeholders ini."
{% endhint %}

***

**Step 1.7: Update JSX to Use State (1 min)**

**Scroll to return statement (\~line 100):**

**BEFORE:**

```javascript
return (
  <ChatShell
    messages={mockMessages}  // ← STATIC data
    status={status}
    error={error}
    onSend={handleSend}
    onClear={handleClear}
  />
);
```

**CHANGE to:**

```javascript
return (
  <ChatShell
    messages={messages}  // ← STATE (dynamic)
    status={status}
    error={error}
    onSend={handleSend}
    onClear={handleClear}
  />
);
```

**Explain:**

{% hint style="info" %}
"Sekarang ChatShell receive `messages` dari state, bukan mockMessages. Ini menghubungkan state ke UI.

Kalau state berubah nanti, ChatShell akan otomatis re-render dengan messages terbaru!"
{% endhint %}

***

**MAJOR DEBUG CHECKPOINT:**

**Action:**

1. Save file
2. Check browser
3. UI should look SAME (3 messages)
4. Check console - see all logs

**Explain to students:**

{% hint style="success" %}
"UI tidak berubah - ini expected! Kenapa?

Initial state value sama dengan mockMessages. Tapi ada perbedaan fundamental:

**Before:** mockMessages = static constant\
**Now:** messages = STATE that can be updated

Sekarang kita punya foundation. Next step: actually update state via user interaction!"
{% endhint %}

***

#### \[PHASE 3: Verification & Understanding Check - 4 minutes]

**Interactive Questions:**

**Q1: Point and Identify**

Show this line:

```javascript
const [messages, setMessages] = useState(mockMessages);
```

Ask: "Tunjuk mana yang state value? Mana yang updater function? Mana yang initial value?"

**Expected answers:**

* `messages` = state value
* `setMessages` = updater function
* `mockMessages` = initial value

***

**Q2: What Happens If...**

Ask: "Kalau saya tulis `messages.push(newMessage)`, apa yang terjadi?"

**Expected answers:**

* UI tidak update
* State mutated (bad!)
* React tidak detect change

**Demo the WRONG way (intentionally):**

```javascript
function handleSend(text) {
  // ⚠️ DEMO ONLY - THIS IS WRONG!
  console.log("Before push:", messages.length);
  
  messages.push({
    id: 'm4',
    role: 'user',
    content: text
  });
  
  console.log("After push:", messages.length);
  console.log("Messages array:", messages);
}
```

**Action:**

1. Type a message in UI
2. Press send
3. Check console

**Show to students:**

```
Before push: 3
After push: 4
Messages array: (4) [{…}, {…}, {…}, {…}]  ← Array has 4 items!
```

**But:** UI still shows only 3 messages!

**Explain:**

{% hint style="danger" %}
"Lihat! Console shows 4 messages, tapi UI cuma show 3. Kenapa?

**React checks state by REFERENCE (memory address):**

```
push() mutates array → same reference → React thinks no change → no re-render
```

**The right way:**

```javascript
setMessages([...messages, newMessage])  // New array = new reference
```

Kita akan implement cara yang benar di Step 2!"
{% endhint %}

**UNDO the demo code!** Make sure to remove the wrong code.

***

**Q3: When Is Initial Value Used?**

Ask: "Initial value `mockMessages` dipanggil setiap render?"

**Expected answer:** No, hanya sekali saat mount

**Explain:**

{% hint style="info" %}
"React 'remember' state. Initial value hanya untuk bootstrap. Di render berikutnya, React load state dari memory.

**For expensive initialization:**

```javascript
// ❌ Runs every render (wasteful)
const [data, setData] = useState(expensiveFunction());

// ✅ Runs once (lazy initialization)
const [data, setData] = useState(() => expensiveFunction());
```

Lihat THEORY.md section 'Lazy Initialization' untuk detail."
{% endhint %}

***

**Checklist Step 1 Complete:**

* useState imported
* 3 states declared (messages, status, error)
* Console logs show correct values
* Placeholders removed
* JSX updated to use state
* UI still shows 3 messages (no visual change yet)
* Students understand:
  * State vs variable
  * State triggers re-render
  * Mutation vs immutable update
  * Initial value concept

**Time Check:** Should be around 15 minutes from workshop start

***

## STEP 2: Event Handlers & Async Operations (15 minutes)

{% hint style="info" %}
**Section Overview:** Learn how to handle user events, update state immutably, and manage async operations.
{% endhint %}

#### \[PHASE 1: Theory - 3 minutes]

**THEORY REFERENCE:** `THEORY.md` - "Immutable Updates" and "Functional Updates" sections

**Talking Points:**

#### 1. React Event Flow (1 min)

**Diagram: React Event Flow**

```
User Action (click, type, etc)
       ↓
Event Handler Function
       ↓
setState Called
       ↓
React Schedules Re-Render
       ↓
Component Re-Renders
       ↓
New JSX Returned
       ↓
DOM Updated
       ↓
User Sees Changes
```

**Explain:**

{% hint style="info" %}
"Ini flow normal React. User action trigger handler, handler update state, state change trigger re-render, UI update."
{% endhint %}

***

#### 2. Immutable State Updates (1 min)

**Write comparison on screen:**

```javascript
// ❌ WRONG: Mutation
const newMessages = messages;
newMessages.push(newMsg);
setMessages(newMessages);
// Same reference! React won't re-render

// ✅ CORRECT: Create new array
setMessages([...messages, newMsg]);
// New reference! React will re-render
```

**Key concept:**

{% hint style="danger" %}
"React compares state by **reference (===)**, not by value.

Same reference = React assumes no change = no re-render\
New reference = React knows changed = re-render

**Always create NEW array/object when updating!"**
{% endhint %}

**Common immutable patterns:**

| Operation     | Wrong              | Correct                                        |
| ------------- | ------------------ | ---------------------------------------------- |
| Add item      | `arr.push(x)`      | `[...arr, x]`                                  |
| Remove item   | `arr.splice(i, 1)` | `arr.filter((_, idx) => idx !== i)`            |
| Update item   | `arr[i] = x`       | `arr.map((item, idx) => idx === i ? x : item)` |
| Update object | `obj.prop = x`     | `{ ...obj, prop: x }`                          |

***

#### 3. Functional Updates (1 min)

**Show the problem:**

```javascript
// ⚠️ PROBLEM: Stale Closure
function handleClick() {
  setCount(count + 1);  // count = 0
  setCount(count + 1);  // count still 0! (stale)
  // Result: count becomes 1, not 2!
}

// ✅ SOLUTION: Functional Update
function handleClick() {
  setCount(prev => prev + 1);  // prev = 0 → returns 1
  setCount(prev => prev + 1);  // prev = 1 → returns 2
  // Result: count becomes 2 ✅
}
```

**Explain:**

{% hint style="warning" %}
"**When to use functional updates:**

* New state depends on old state
* Inside async functions (setTimeout, fetch)
* Multiple updates in same event
* Inside useEffect/useCallback

**Rule of thumb:** If you see `setState(stateValue + something)`, use functional update instead!"
{% endhint %}

**Checklist Theory:**

* Students paham immutable updates
* Students paham spread operator
* Students paham functional updates
* Students paham stale closure problem

***

#### \[PHASE 2: Live Coding handleSend - 8 minutes]

**Goal:** Implement handleSend to add user message + simulate bot response

**Code Location:** `src/components/Chat.jsx` - `handleSend` function (\~line 60)

***

**Step 2.1: Add Input Validation (1 min)**

**Find handleSend function:**

```javascript
function handleSend(text) {
  console.log("SEND:", text);
}
```

**REPLACE with:**

```javascript
function handleSend(text) {
  console.log("📤 SEND called with text:", text);
  
  // Validation: don't send if empty
  if (!text.trim()) {
    console.log("⚠️ Empty text, ignoring");
    return;
  }
  
  console.log("✅ Text valid, proceeding...");
  
  // ... rest will be added
}
```

**Explain:**

{% hint style="info" %}
"Always validate user input! `trim()` removes whitespace. If empty, return early - don't process further."
{% endhint %}

**DEBUG TEST:**

**Action:**

1. Save file
2. Go to browser
3. Try send empty message (just spaces)
4. Check console

**Should see:**

```
📤 SEND called with text: "   "
⚠️ Empty text, ignoring
```

**Try send real message:**

```
📤 SEND called with text: "Hello"
✅ Text valid, proceeding...
```

***

**Step 2.2: Create User Message Object (1 min)**

**Add after validation:**

```javascript
// Create user message object
const userMessage = {
  id: `m${Date.now()}`,  // Simple unique ID using timestamp
  role: 'user',
  content: text
};

console.log("👤 User message created:", userMessage);
```

**Explain:**

{% hint style="info" %}
"Message object structure:

* `id`: Unique identifier. Pakai timestamp untuk simplicity (production pakai UUID)
* `role`: 'user' atau 'model' untuk styling
* `content`: The actual text

Structure ini match dengan mockMessages structure."
{% endhint %}

***

**Step 2.3: Update Messages State (2 min)**

**Add after user message creation:**

```javascript
// Update messages state dengan functional update
setMessages(prev => {
  console.log("📦 Previous messages:", prev.length);
  const newMessages = [...prev, userMessage];
  console.log("📦 New messages:", newMessages.length);
  return newMessages;
});

console.log("✅ State update scheduled");
```

**Explain while typing:**

{% hint style="info" %}
"**Functional update breakdown:**

`setMessages(prev => ...)`

* `prev` = guaranteed latest messages value
* Even if this function runs multiple times, prev always correct

`[...prev, userMessage]`

* Spread operator creates NEW array
* Append userMessage to end
* Immutable update ✅

**Why not `[...messages, userMessage]`?**

* `messages` bisa stale (especially in async context)
* `prev` always latest from React

**setState is async:**\
State tidak update immediately. React schedules update dan batch multiple updates untuk performance."
{% endhint %}

**DEBUG CHECKPOINT:**

**Action:**

1. Save file
2. Type message "Hello" in browser
3. Send
4. Check console logs

**Should see:**

```
📤 SEND called with text: "Hello"
✅ Text valid, proceeding...
👤 User message created: {id: 'm1707...', role: 'user', content: 'Hello'}
📦 Previous messages: 3
📦 New messages: 4
✅ State update scheduled
🔄 RENDER: Chat component rendered  ← Re-render!
📦 Messages state: (4) [{…}, {…}, {…}, {…}]  ← 4 messages now!
```

**Point out to students:**

{% hint style="success" %}
"Lihat! Re-render triggered (log '🔄 RENDER' muncul lagi). Messages state sekarang punya 4 items. Dan lihat UI - user message muncul!"
{% endhint %}

**Show in browser:** User message "Hello" should appear as blue bubble on the right.

***

**Step 2.4: Set Loading State (1 min)**

**Add after state update:**

```javascript
// Set status to loading
setStatus('loading');
console.log("⏳ Status set to loading");

// Clear any previous error
setError(null);
console.log("✅ Error cleared");
```

**Explain:**

{% hint style="info" %}
"Set status ke 'loading' untuk show loading indicator. ChatShell akan render 'Thinking...' text.

Clear error karena user trying again - previous error tidak relevant anymore."
{% endhint %}

**DEBUG TEST:**

**Action:**

1. Save file
2. Send message
3. Look at UI immediately

**Should see:** "Thinking..." text appear below messages

***

**Step 2.5: Simulate Async Bot Response (3 min)**

**Add after setting loading:**

```javascript
// Simulate async bot response
console.log("🤖 Starting bot response simulation...");

setTimeout(() => {
  console.log("🤖 Bot response ready");
  
  // Create bot message
  const botMessage = {
    id: `m${Date.now()}`,
    role: 'model',
    content: `Kamu bilang: "${text}". Ini response otomatis dari bot!`
  };
  
  console.log("🤖 Bot message:", botMessage);
  
  // Add bot message to state
  setMessages(prev => {
    console.log("📦 Adding bot message, previous:", prev.length);
    return [...prev, botMessage];
  });
  
  // Reset status to idle
  setStatus('idle');
  console.log("✅ Status reset to idle");
  
}, 1500);  // 1.5 second delay

console.log("⏰ setTimeout scheduled for 1500ms");
```

**Explain in detail:**

{% hint style="info" %}
"**setTimeout simulates async operation:**

Real app = fetch API. Workshop = setTimeout. Kenapa?

* No backend needed
* Easy to understand
* Shows async state management pattern
* Delay makes loading state visible

**Async flow:**

1. User sends → userMessage added → status = 'loading'
2. Wait 1500ms... (simulating API call)
3. Bot response ready → botMessage added → status = 'idle'

**Each setState triggers separate re-render:**

* 1st re-render: userMessage appears + 'Thinking...'
* 2nd re-render: botMessage appears + 'Thinking...' gone

**setTimeout is non-blocking:**\
Code after setTimeout runs immediately. Function inside runs after delay."
{% endhint %}

**Diagram: Async Timeline**

```
t=0ms:     handleSend called
           ├─ userMessage added
           ├─ status = 'loading'
           ├─ setTimeout scheduled
           └─ handleSend returns

t=0ms:     Re-render (userMessage visible, "Thinking...")

t=1500ms:  setTimeout callback runs
           ├─ botMessage added
           └─ status = 'idle'

t=1500ms:  Re-render (botMessage visible, no "Thinking...")
```

***

**MAJOR DEBUG CHECKPOINT:**

**Action:**

1. Save file
2. Clear console
3. Send message "Test async"
4. Watch console logs in real-time
5. Watch UI changes

**Expected console output:**

```
📤 SEND called with text: "Test async"
✅ Text valid, proceeding...
👤 User message created: {id: 'm...', role: 'user', content: 'Test async'}
📦 Previous messages: 3
📦 New messages: 4
✅ State update scheduled
⏳ Status set to loading
✅ Error cleared
🤖 Starting bot response simulation...
⏰ setTimeout scheduled for 1500ms
🔄 RENDER: Chat component rendered  ← 1st re-render
📦 Messages state: (4) [{…}, {…}, {…}, {…}]
🚦 Status state: loading
(... 1.5 seconds pass ...)
🤖 Bot response ready
🤖 Bot message: {id: 'm...', role: 'model', content: 'Kamu bilang...'}
📦 Adding bot message, previous: 4
✅ Status reset to idle
🔄 RENDER: Chat component rendered  ← 2nd re-render
📦 Messages state: (5) [{…}, {…}, {…}, {…}, {…}]
🚦 Status state: idle
```

**Point out to students:**

{% hint style="success" %}
"**Perhatikan:**

1. Two re-renders (one for user message, one for bot)
2. Status changes: idle → loading → idle
3. Messages grow: 3 → 4 → 5
4. 'Thinking...' appears then disappears
5. Bot response includes user's text

Ini adalah **async state management pattern**. Kita track process dengan multiple states (messages + status)."
{% endhint %}

**Show in browser:**

* User message appears immediately (blue, right side)
* "Thinking..." appears
* 1.5 seconds later, bot response appears (gray, left side)
* "Thinking..." disappears

***

#### \[PHASE 3: Implement handleClear - 2 minutes]

**Find handleClear function (\~line 90):**

```javascript
function handleClear() {
  console.log("CLEAR");
}
```

**REPLACE with:**

```javascript
function handleClear() {
  console.log("🗑️ CLEAR called");
  
  // Reset all states
  setMessages([]);
  console.log("📦 Messages cleared");
  
  setStatus('idle');
  console.log("🚦 Status reset to idle");
  
  setError(null);
  console.log("⚠️ Error cleared");
  
  console.log("✅ All states reset");
}
```

**Explain:**

{% hint style="info" %}
"Clear function resets everything to initial state.

**Multiple setState in one function:**\
React batches them = single re-render (performance optimization)

Alternative: could reset to `mockMessages` instead of `[]` if you want default messages to stay."
{% endhint %}

**DEBUG TEST:**

**Action:**

1. Save file
2. Send a few messages
3. Click "Clear" button
4. Check console

**Expected:**

```
🗑️ CLEAR called
📦 Messages cleared
🚦 Status reset to idle
⚠️ Error cleared
✅ All states reset
🔄 RENDER: Chat component rendered
📦 Messages state: []  ← Empty array
```

**Show in browser:** All messages disappear.

***

#### \[PHASE 4: Verification & Understanding Check - 2 minutes]

**Interactive Questions:**

**Q1: Immutable Update**

Show this code:

```javascript
// Option A
setMessages([...messages, newMessage]);

// Option B
messages.push(newMessage);
setMessages(messages);
```

Ask: "Which one is correct? Why?"

**Expected answer:**

* Option A correct
* Option B wrong (same reference)
* Must create new array

***

**Q2: Functional Update**

Ask: "Kenapa kita pakai `prev => [...prev, msg]` instead of `[...messages, msg]`?"

**Expected answer:**

* Avoid stale closure
* `prev` guaranteed latest
* Safe in async contexts

***

**Q3: Async Flow**

Ask: "Berapa kali component re-render saat user send message?"

**Expected answer:**

* 2 times
* 1st: user message + loading
* 2nd: bot message + idle

***

**Checklist Step 2 Complete:**

* handleSend implemented
* Input validation works
* User message appears immediately
* Loading indicator shows
* Bot response appears after delay
* handleClear works
* Multiple messages work correctly
* Students understand:
  * Immutable updates
  * Functional updates
  * Async state management
  * State batching

**Time Check:** Should be around 30 minutes from workshop start

***

## STEP 3: Error Handling (8 minutes)

{% hint style="info" %}
**Section Overview:** Implement error handling as UI state to provide better user experience.
{% endhint %}

#### \[PHASE 1: Theory - 2 minutes]

**THEORY REFERENCE:** `THEORY.md` - "Common Patterns" section (State Machine Pattern)

**Talking Points:**

#### Error as UI State (2 min)

**Show comparison:**

```javascript
// ❌ BAD: Error as side effect
function handleSend(text) {
  try {
    // ... code
  } catch (err) {
    console.error(err);  // Developer sees, user doesn't!
  }
}

// ✅ GOOD: Error as UI state
function handleSend(text) {
  try {
    // ... code
  } catch (err) {
    setError(err.message);  // User sees error in UI!
    setStatus('error');     // UI shows error state
  }
}
```

**Explain:**

{% hint style="info" %}
"Errors are part of user experience. Users need to know:

1. Something went wrong
2. What went wrong (error message)
3. What they can do (retry, change input, etc)

**Error handling pattern:**

* Catch error
* Set error state (message for user)
* Set status state ('error' for UI)
* Show error UI (red banner, icon, etc)
* Allow recovery (user can retry)

ChatShell already handles error UI. We just need to set state."
{% endhint %}

**Checklist Theory:**

* Students paham error = UI state
* Students paham error recovery pattern

***

#### \[PHASE 2: Live Coding - 4 minutes]

**Goal:** Add error trigger and handling

**IMPORTANT: Make sure error state is declared in Step 1!**

{% hint style="danger" %}
**Common Issue: Error doesn't show?**

Check that you have declared error state in Step 1:

```javascript
const [error, setError] = useState(null);
```

Without this, `setError()` will cause "setError is not defined" error!
{% endhint %}

**Find handleSend, after validation, BEFORE creating userMessage:**

```javascript
function handleSend(text) {
  console.log("📤 SEND called with text:", text);
  
  if (!text.trim()) {
    console.log("⚠️ Empty text, ignoring");
    return;
  }
  
  console.log("✅ Text valid, proceeding...");
  
  // ========== ADD ERROR HANDLING HERE ==========
  
  // Check for error trigger (demo purposes)
  if (text.toLowerCase().includes('error')) {
    console.log("🚨 Error trigger detected!");
    
    setStatus('error');
    console.log("🚦 Status set to error");
    
    setError('Simulasi error: kata "error" terdeteksi! Coba kata lain.');
    console.log("⚠️ Error message set");
    
    return;  // Stop execution, don't send message
  }
  
  // ========== CONTINUE WITH NORMAL FLOW ==========
  
  // Clear any previous errors (error recovery)
  setError(null);
  console.log("✅ Previous errors cleared");
  
  // Create user message
  const userMessage = {
    id: `m${Date.now()}`,
    role: 'user',
    content: text
  };
  
  console.log("📝 User message created:", userMessage.id);
  
  // Add user message to state
  setMessages(prev => [...prev, userMessage]);
  console.log("📦 Messages updated with user message");
  
  // Set loading status
  setStatus('loading');
  console.log("🚦 Status set to loading");
  
  // Simulate bot response (async)
  setTimeout(() => {
    const botMessage = {
      id: `m${Date.now()}`,
      role: 'model',
      content: `Kamu bilang: "${text}"`
    };
    
    console.log("🤖 Bot message created:", botMessage.id);
    
    setMessages(prev => [...prev, botMessage]);
    console.log("📦 Messages updated with bot message");
    
    setStatus('idle');
    console.log("🚦 Status back to idle");
  }, 1500);
}
```

**Complete Chat.jsx at this point should look like:**

```javascript
import { useState } from 'react';
import ChatShell from "./ChatShell";

const mockMessages = [
  { id: "m1", role: "model", content: "Halo! Aku chatbot 🙂" },
  { id: "m2", role: "user", content: "Nanti kita fokus ke hooks ya?" },
  { id: "m3", role: "model", content: "Yes. Mulai dari useState sampai custom hook." },
];

export default function Chat() {
  // STEP 1: State Management
  const [messages, setMessages] = useState(mockMessages);
  const [status, setStatus] = useState('idle');
  const [error, setError] = useState(null);  // ← MUST HAVE THIS!
  
  // STEP 2 & 3: Event Handlers with Error Handling
  function handleSend(text) {
    if (!text.trim()) return;
    
    // Error trigger
    if (text.toLowerCase().includes('error')) {
      setStatus('error');
      setError('Simulasi error: kata "error" terdeteksi!');
      return;
    }
    
    // Clear previous errors
    setError(null);
    
    // User message
    const userMessage = {
      id: `m${Date.now()}`,
      role: 'user',
      content: text
    };
    
    setMessages(prev => [...prev, userMessage]);
    setStatus('loading');
    
    // Bot response
    setTimeout(() => {
      const botMessage = {
        id: `m${Date.now()}`,
        role: 'model',
        content: `Kamu bilang: "${text}"`
      };
      
      setMessages(prev => [...prev, botMessage]);
      setStatus('idle');
    }, 1500);
  }
  
  function handleClear() {
    setMessages([]);
    setStatus('idle');
    setError(null);  // ← Clear error on clear
  }
  
  return (
    <ChatShell
      messages={messages}
      status={status}
      error={error}  // ← Pass error prop to ChatShell
      onSend={handleSend}
      onClear={handleClear}
    />
  );
}
```

**Explain:**

{% hint style="info" %}
"**Error trigger for demo:**\
If user types word 'error', we simulate an error. Real app = API error, network error, validation error, etc.

**Error handling steps:**

1. Detect error condition
2. Set status to 'error'
3. Set error message (user-friendly!)
4. Return early (stop normal flow)

**UI response:**\
ChatShell will show red error banner with message.

**How ChatShell displays error:**

ChatShell checks status and error props:

```javascript
// Inside ChatShell.jsx (already implemented)
{status === "error" && (
  <div className="mt-4 rounded-xl border border-red-200 bg-red-50 p-3 text-sm text-red-700">
    {error || "Terjadi kesalahan."}
  </div>
)}
```

When `status === 'error'`, red banner appears with error message!"
{% endhint %}

***

**DEBUG TEST - Trigger Error:**

**Action:**

1. Save file
2. Clear console
3. Type "this is error" in chat
4. Send
5. Watch console and UI

**Expected console:**

```
📤 SEND called with text: "this is error"
✅ Text valid, proceeding...
🚨 Error trigger detected!
🚦 Status set to error
⚠️ Error message set
🔄 RENDER: Chat component rendered
🚦 Status state: error
⚠️ Error state: "Simulasi error: kata \"error\" terdeteksi! Coba kata lain."
```

**Expected UI:**

* Red error banner appears below messages
* Error message displayed
* No user message added

**Point out:**

{% hint style="success" %}
"Error state causes UI to show error banner. User sees clear feedback about what went wrong."
{% endhint %}

***

**DEBUG TEST - Error Recovery:**

**Action:**

1. After error shows, type normal message "hello"
2. Send
3. Watch error disappear

**Expected:**

* User message "hello" added
* Error banner disappears
* Bot responds normally

**Explain:**

{% hint style="success" %}
"Error recovery works automatically! Kenapa?

In handleSend, we have:

```javascript
setError(null);  // Clear any previous error
```

Every successful send clears old error. This is **error recovery pattern**."
{% endhint %}

***

#### \[PHASE 3: Verification - 2 minutes]

**Interactive Test with Students:**

**Test 1:** "Coba ketik 'error test' dan send"

* Should show error
* No message added

**Test 2:** "Sekarang ketik 'hello' dan send"

* Error disappears
* Message added
* Bot responds

**Test 3:** "Coba ketik 'my ERROR message'"

* Should trigger error (case-insensitive)

**Q\&A:**

**Q1:** "Kapan error state di-clear?"

**Expected answer:**

* Saat user send message baru
* Di handleClear
* Automatic recovery

**Q2:** "Bisa ada error dan loading bersamaan?"

**Expected answer:**

* No! Status machine - hanya satu state
* Either idle, loading, OR error

***

**Checklist Step 3 Complete:**

* Error handling implemented
* Error trigger works
* Error message shows in UI
* Error recovery works
* Students understand:
  * Error as UI state
  * State machine pattern
  * Error recovery pattern

**Time Check:** Should be around 38 minutes from workshop start

***

## STEP 4: useEffect - Side Effects (12 minutes)

{% hint style="info" %}
**Section Overview:** Learn how to perform side effects after render using useEffect hook.
{% endhint %}

#### \[PHASE 1: Theory - 4 minutes]

**THEORY REFERENCE:** `THEORY.md` - "useEffect - Side Effects" section

**Talking Points:**

#### 1. What are Side Effects? (2 min)

**Write definition:**

{% hint style="info" %}
"Side Effect = Anything that affects 'outside world' beyond returning JSX"
{% endhint %}

**Examples:**

| Side Effect      | Why?                            |
| ---------------- | ------------------------------- |
| DOM manipulation | Changes DOM outside React       |
| API calls        | Network I/O                     |
| Subscriptions    | External state changes          |
| Timers           | Async operations                |
| localStorage     | Browser API                     |
| console.log      | (technically, but OK for debug) |

**Show the problem:**

```javascript
// ❌ WRONG: Side effect during render
function Chat() {
  document.title = `${messages.length} messages`;  // Side effect!
  
  return <div>...</div>;
}

// ⚠️ PROBLEMS:
// - Strict Mode calls render 2x = title set 2x
// - Render can be interrupted/retried
// - Not predictable
```

**Show the solution:**

```javascript
// ✅ CORRECT: Side effect in useEffect
function Chat() {
  useEffect(() => {
    document.title = `${messages.length} messages`;  // Safe!
  }, [messages.length]);
  
  return <div>...</div>;
}

// ✅ BENEFITS:
// - Runs AFTER commit to DOM
// - Predictable timing
// - Can cleanup
```

***

#### 2. useEffect Syntax (2 min)

**Write on screen:**

```javascript
useEffect(() => {
  // Effect code (runs after render committed)
  
  return () => {
    // Cleanup (runs before next effect or unmount)
  };
}, [dependencies]);
//  ↑ Controls when effect re-runs
```

**Explain each part:**

{% hint style="info" %}
"**Effect function:** Runs after React commits changes to DOM. This is where you do side effects.

**Cleanup function (optional):** Runs before next effect or when component unmounts. Use for:

* Unsubscribe
* Clear timers
* Remove event listeners
* Cancel API calls

**Dependencies array:** Controls when effect re-runs."
{% endhint %}

**Dependencies patterns:**

```javascript
// No array → run every render (usually wrong!)
useEffect(() => {
  console.log("Every render!");
});

// Empty [] → run once on mount
useEffect(() => {
  console.log("Once on mount!");
}, []);

// [dep] → run when dep changes
useEffect(() => {
  console.log("When messages change!");
}, [messages.length]);
```

**Diagram: useEffect Lifecycle**

```
Mount → Effect runs
  ↓
Update (dep changes) → Cleanup runs → Effect runs again
  ↓
Unmount → Cleanup runs
```

**Checklist Theory:**

* Students paham side effects concept
* Students paham useEffect syntax
* Students paham dependencies array
* Students paham cleanup concept

***

#### \[PHASE 2: Live Coding - 6 minutes]

**Goal:** Add useEffect for auto-scroll when messages change

**Step 4.1: Import useEffect (1 min)**

**Find line 1:**

```javascript
import { useState } from "react";
```

**UPDATE to:**

```javascript
import { useState, useEffect } from "react";
```

**Explain:**

{% hint style="info" %}
"Import useEffect dari React. Named export, sama seperti useState."
{% endhint %}

***

**Step 4.2: Add useEffect (2 min)**

**Find location:** After all state declarations, before handlers (\~line 50)

**TYPE:**

```javascript
// Side effect: Auto-scroll when messages change
useEffect(() => {
  console.log("🎯 useEffect triggered");
  console.log("📊 Messages length:", messages.length);
  
  // Scroll effect will be added with ref in Step 5
  // For now, just log to show effect running
  
}, [messages.length]);
//  ↑ Dependency: re-run when messages.length changes

console.log("📝 useEffect registered (will run after render)");
```

**Explain while typing:**

{% hint style="info" %}
"**useEffect breakdown:**

```javascript
useEffect(() => { ... }, [messages.length]);
```

**Effect function:** Logs untuk show when it runs. Nanti kita tambahkan scroll code.

**Dependencies \[messages.length]:**

* Effect re-runs when messages.length changes
* Not when other states change (status, error)
* Not on every render

**Why .length not messages?**

* `messages` is array → new reference every update → effect runs every time
* `messages.length` is number → only changes when messages added/removed
* More efficient!

**Timing:** Effect runs AFTER render committed. Console log outside useEffect runs during render."
{% endhint %}

***

**DEBUG CHECKPOINT - Understanding Timing:**

**Action:**

1. Save file
2. Clear console
3. Send a message
4. Watch console logs carefully

**Expected console output:**

```
📤 SEND called with text: "test"
✅ Text valid, proceeding...
👤 User message created: ...
📦 Previous messages: 3
📦 New messages: 4
...
📝 useEffect registered (will run after render)  ← During render
🔄 RENDER: Chat component rendered
📦 Messages state: (4) [...]
🚦 Status state: loading
📝 useEffect registered (will run after render)  ← During render again
🎯 useEffect triggered  ← AFTER render!
📊 Messages length: 4

(... wait 1.5s ...)

📝 useEffect registered (will run after render)
🔄 RENDER: Chat component rendered
📦 Messages state: (5) [...]
📝 useEffect registered (will run after render)
🎯 useEffect triggered  ← AFTER render again!
📊 Messages length: 5
```

**Point out to students:**

{% hint style="success" %}
"**Notice the order:**

1. Code runs top to bottom (render phase)
2. '📝 useEffect registered' during render
3. React commits changes to DOM
4. '🎯 useEffect triggered' AFTER commit

**Effect runs twice:**

* Once when user message added (4 messages)
* Again when bot message added (5 messages)

Effect automatically responds to messages changes!"
{% endhint %}

***

**Step 4.3: Explain Dependencies (2 min)**

**Show comparison on screen:**

```javascript
// ❌ Missing dependency (eslint warning)
useEffect(() => {
  console.log(messages.length);  // Uses messages.length
}, []);  // But not in deps!
// Effect won't re-run when messages change

// ✅ Correct dependencies
useEffect(() => {
  console.log(messages.length);
}, [messages.length]);  // messages.length in deps!
// Effect re-runs when messages change

// ⚠️ Too many dependencies
useEffect(() => {
  console.log(messages.length);
}, [messages, status, error]);  // Overkill!
// Effect runs when status/error change (unnecessary)
```

**Explain:**

{% hint style="warning" %}
"**Rules for dependencies:**

1. Include all values from component scope that effect uses
2. ESLint rule `exhaustive-deps` checks this
3. Too few deps = stale values, bugs
4. Too many deps = runs too often, performance

**Exceptions (no need in deps):**

* setState functions (stable)
* ref.current (mutable, not reactive)
* Constants outside component"
  {% endhint %}

***

**DEBUG TEST - Dependencies:**

**Try removing dependency:**

```javascript
useEffect(() => {
  console.log("Effect:", messages.length);
}, []);  // Empty array!
```

**Action:**

1. Save
2. Look for ESLint warning (squiggly line)
3. Hover to see warning message

**Should see:**

```
React Hook useEffect has a missing dependency: 'messages.length'.
Either include it or remove the dependency array.
```

**Explain:**

{% hint style="danger" %}
"ESLint warns us! Missing dependency = potential bug. Effect won't update when messages change.

Always fix these warnings. They prevent bugs!"
{% endhint %}

**REVERT to correct version:**

```javascript
useEffect(() => {
  console.log("Effect:", messages.length);
}, [messages.length]);  // Correct!
```

***

#### \[PHASE 3: Verification - 2 minutes]

**Interactive Questions:**

**Q1:** "Effect jalan kapan? Sebelum atau sesudah DOM update?"

**Expected answer:** Sesudah (after commit)

***

**Q2:** "Kalau dependency array kosong \[], kapan effect jalan?"

**Expected answer:** Sekali saat mount

***

**Q3:** "Kenapa pakai messages.length bukan messages?"

**Expected answer:**

* messages new reference every update
* .length only changes when items added/removed
* More efficient

***

**Q4:** "Effect ini jalan berapa kali saat user send message?"

**Expected answer:**

* 2 kali
* 1st: user message added
* 2nd: bot message added

***

**Checklist Step 4 Complete:**

* useEffect imported
* useEffect implemented
* Dependencies correct (\[messages.length])
* Console logs show effect timing
* Students understand:
  * Side effects concept
  * Effect runs after render
  * Dependencies control re-runs
  * ESLint helps catch bugs

**Note:** Actual scroll implementation akan ditambahkan di Step 5 setelah kita punya ref!

**Time Check:** Should be around 50 minutes from workshop start

***

## STEP 5: useRef - DOM References (10 minutes)

{% hint style="info" %}
**Section Overview:** Learn how to use useRef for DOM manipulation and mutable values that don't trigger re-renders.
{% endhint %}

#### \[PHASE 1: Theory - 3 minutes]

**THEORY REFERENCE:** `THEORY.md` - "useRef - Mutable References" section

**Talking Points:**

#### 1. What is useRef? (2 min)

**Write definition:**

{% hint style="info" %}
"useRef is a 'container' for mutable values that persist across renders WITHOUT triggering re-render"
{% endhint %}

**Show comparison table:**

|                | useState        | useRef              |
| -------------- | --------------- | ------------------- |
| **Value**      | `state`         | `ref.current`       |
| **Update**     | `setState(new)` | `ref.current = new` |
| **Mutability** | Immutable       | Mutable             |
| **Re-render?** | Yes             | No                  |
| **Use for**    | UI data         | Non-UI data         |

**Code comparison:**

```javascript
// useState
const [count, setCount] = useState(0);
setCount(1);  // Triggers re-render

// useRef
const countRef = useRef(0);
countRef.current = 1;  // NO re-render
```

**Demonstrate the difference:**

```javascript
function Demo() {
  const [count, setCount] = useState(0);
  const renderCount = useRef(0);
  
  // Increment render counter (every render)
  renderCount.current = renderCount.current + 1;
  
  return (
    <div>
      <p>Count (state): {count}</p>
      <p>Renders (ref): {renderCount.current}</p>
      
      <button onClick={() => setCount(count + 1)}>
        Increment Count (will re-render)
      </button>
      
      <button onClick={() => renderCount.current++}>
        Increment Ref (NO re-render - won't see change!)
      </button>
    </div>
  );
}
```

**Explain:**

{% hint style="warning" %}
"Ref changes don't cause re-render. That's the point! Use ref for values you need to 'remember' but don't need to show in UI."
{% endhint %}

***

#### 2. Use Cases for useRef (1 min)

**List use cases:**

```
1. DOM references (most common)
   - ref.current = DOM element
   - For focus, scroll, measure, etc

2. Store timer IDs
   - setInterval/setTimeout IDs
   - For cleanup

3. Store previous values
   - Compare current vs previous
   - Track changes

4. Store instances
   - WebSocket, EventSource
   - Any external object
```

**For this workshop:** We use ref for DOM reference (scroll target)

**Checklist Theory:**

* Students paham ref vs state
* Students paham ref mutable
* Students paham ref no re-render
* Students paham use cases

***

#### \[PHASE 2: Live Coding - 5 minutes]

**Goal:** Add ref for scroll target and implement auto-scroll

**Step 5.1: Import useRef (1 min)**

**Find line 1:**

```javascript
import { useState, useEffect } from "react";
```

**UPDATE to:**

```javascript
import { useState, useEffect, useRef } from "react";
```

***

**Step 5.2: Create bottomRef (1 min)**

**Find location:** After state declarations, before useEffect (\~line 45)

**TYPE:**

```javascript
// Ref for scroll target element
const bottomRef = useRef(null);
console.log("📍 bottomRef created:", bottomRef);
console.log("📍 bottomRef.current:", bottomRef.current);
```

**Explain:**

{% hint style="info" %}
"**useRef syntax:**

```javascript
const bottomRef = useRef(null);
```

* `bottomRef` = ref object (stable across renders)
* `bottomRef.current` = the actual value (starts as null)
* `null` = initial value (because DOM doesn't exist yet)

After render, React will set `.current` to the DOM element we attach it to."
{% endhint %}

**DEBUG CHECKPOINT:**

**Action:**

1. Save
2. Check console

**Should see:**

```
📍 bottomRef created: {current: null}
📍 bottomRef.current: null
```

**Explain:**

{% hint style="success" %}
"Ref created, but .current is null karena DOM belum ada. After render, when we attach ref to element, .current akan berisi DOM element."
{% endhint %}

***

**Step 5.3: Implement Scroll in useEffect (2 min)**

**Find useEffect, UPDATE to:**

```javascript
useEffect(() => {
  console.log("🎯 useEffect triggered");
  console.log("📊 Messages length:", messages.length);
  console.log("📍 bottomRef.current:", bottomRef.current);
  
  // Scroll to bottom element
  if (bottomRef.current) {
    console.log("📜 Scrolling to bottom...");
    
    bottomRef.current.scrollIntoView({
      behavior: 'smooth',  // Smooth animation
      block: 'nearest'     // Scroll to nearest edge
    });
    
    console.log("✅ Scroll complete");
  } else {
    console.log("⚠️ bottomRef.current is null, can't scroll");
  }
  
}, [messages.length]);
```

**Explain:**

{% hint style="info" %}
"**Scroll implementation:**

`bottomRef.current?.scrollIntoView()`

* `bottomRef.current` = DOM element
* `scrollIntoView()` = browser API to scroll element into view
* `behavior: 'smooth'` = animated scrolling

**Why if check?**

* .current bisa null (before ref attached)
* Optional chaining (?.) alternative: `bottomRef.current?.scrollIntoView()`

**Timing perfect:**

* useEffect runs after DOM update
* DOM has new messages
* Scroll to bottom to show latest"
  {% endhint %}

***

**Step 5.4: Attach Ref to DOM Element (1 min)**

**Note:** We need to add a scroll target inside ChatShell, but ChatShell doesn't accept children. Let's use Approach B (simpler):

**UPDATE useEffect:**

```javascript
useEffect(() => {
  console.log("🎯 useEffect triggered");
  console.log("📊 Messages length:", messages.length);
  
  // Alternative: scroll to last message
  const chatContainer = document.querySelector('.overflow-y-auto');
  
  if (chatContainer) {
    console.log("📜 Scrolling chat container...");
    
    chatContainer.scrollTop = chatContainer.scrollHeight;
    
    console.log("✅ Scroll complete");
  }
  
}, [messages.length]);
```

**Explain:**

{% hint style="info" %}
"**Alternative approach:**\
Instead of adding new element, we scroll the existing chat container.

`chatContainer.scrollTop = chatContainer.scrollHeight`

* scrollTop = current scroll position
* scrollHeight = total scrollable height
* Setting scrollTop to scrollHeight = scroll to bottom

**Trade-off:**

* No component changes needed
* Works with existing structure
* Direct DOM query (less React-y)

**In real project:** Better to pass ref through props or use forwardRef. But this works for learning!"
{% endhint %}

***

**MAJOR DEBUG CHECKPOINT:**

**Action:**

1. Save file
2. Clear console
3. Send multiple messages quickly
4. Watch auto-scroll behavior

**Expected:**

* Each new message triggers scroll
* Chat automatically stays at bottom
* Smooth scrolling (if you slow down)

**Console shows:**

```
🎯 useEffect triggered
📊 Messages length: 4
📜 Scrolling chat container...
✅ Scroll complete
```

**Point out:**

{% hint style="success" %}
"Auto-scroll works! Setiap message baru, useEffect triggered, scroll ke bawah. User always sees latest message.

**This is side effect pattern:**

* Messages change (state update)
* Effect runs (after render)
* Scroll happens (side effect)

Separation of concerns: state management vs side effects!"
{% endhint %}

***

#### \[PHASE 3: Verification - 2 minutes]

**Interactive Questions:**

**Q1:** "Ref ini mutable atau immutable?"

**Expected answer:** Mutable (bisa ubah .current langsung)

***

**Q2:** "Kalau saya ubah `ref.current = newValue`, apa component re-render?"

**Expected answer:** No! That's the difference from state

***

**Q3:** "Kapan pakai ref, kapan pakai state?"

**Expected answer:**

| Criteria           | useState        | useRef            |
| ------------------ | --------------- | ----------------- |
| Show in UI?        | Yes             | No                |
| Trigger re-render? | Need            | Don't need        |
| Example            | messages, error | timer ID, DOM ref |

***

**Q4:** "Effect jalan sebelum atau sesudah scroll?"

**Expected answer:** Effect runs, then scroll happens inside effect

***

**Checklist Step 5 Complete:**

* useRef imported
* bottomRef created
* Scroll implemented in useEffect
* Auto-scroll works
* Students understand:
  * Ref vs state difference
  * Ref for DOM references
  * Ref mutable, no re-render
  * Side effect (scroll) in useEffect

**Time Check:** Should be around 60 minutes from workshop start

***

## STEP 6: Custom Hook Refactoring (20 minutes)

{% hint style="info" %}
**Section Overview:** Refactor all logic into a custom hook for better code organization and reusability.
{% endhint %}

#### \[PHASE 1: Theory - 4 minutes]

**THEORY REFERENCE:** `THEORY.md` - "Custom Hooks - Reusable Logic" section

**Talking Points:**

#### 1. Why Custom Hooks? (2 min)

**Show the problem:**

```javascript
// Current Chat.jsx
function Chat() {
  // 50+ lines of logic:
  const [messages, setMessages] = useState(...);
  const [status, setStatus] = useState(...);
  const [error, setError] = useState(...);
  const bottomRef = useRef(...);
  
  useEffect(() => {
    // scroll logic
  }, [messages.length]);
  
  function handleSend(text) {
    // 20+ lines
  }
  
  function handleClear() {
    // 5+ lines
  }
  
  // 10+ lines of JSX
  return <ChatShell ... />;
}
```

**Problems:**

* Component "fat" (too many responsibilities)
* Logic dan UI mixed
* Hard to test logic separately
* Can't reuse logic in other components
* Violates Single Responsibility Principle

**The solution: Custom Hook**

```javascript
// After refactoring

// hooks/useChat.js (reusable logic)
function useChat() {
  // All logic here
  return { messages, status, error, sendMessage, clearChat };
}

// components/Chat.jsx (clean UI)
function Chat() {
  const chat = useChat();  // 1 line!
  
  return <ChatShell {...chat} />;  // UI only
}
```

**Benefits:**

* Separation of concerns (UI vs logic)
* Component stays clean and focused
* Logic is reusable
* Logic is testable in isolation
* Easier to maintain

***

#### 2. Custom Hook Rules (2 min)

**Essential rules:**

```
1. Name MUST start with "use"
   ✅ useChat, useFetch, useToggle
   ❌ chatHook, getMessages

2. Can call other hooks
   ✅ Can use useState, useEffect, etc inside
   
3. Must follow Rules of Hooks
   ✅ Call at top level only
   ❌ No conditionals/loops around hooks

4. Return anything you want
   ✅ Object: { value1, value2, fn1 }
   ✅ Array: [value, setValue]
   ✅ Just value: value
```

**Naming convention:**

```javascript
// ✅ GOOD: Clear, starts with "use"
function useChat() { }
function useWindowSize() { }
function useLocalStorage() { }

// ❌ BAD: Doesn't start with "use"
function chatManager() { }  // React won't recognize as hook
function getMessages() { }  // ESLint rules won't apply
```

**Return patterns:**

```javascript
// Pattern 1: Object (for multiple named returns)
function useChat() {
  return {
    messages,
    status,
    sendMessage,  // Named properties
    clearChat
  };
}
// Usage: const { messages, sendMessage } = useChat();

// Pattern 2: Array (like useState)
function useToggle(initial) {
  const [value, setValue] = useState(initial);
  const toggle = () => setValue(!value);
  
  return [value, toggle];  // Positional
}
// Usage: const [isOpen, toggleOpen] = useToggle(false);
```

**When to use which?**

* **Object:** Multiple values (>2), clarity important
* **Array:** 1-2 values, flexible naming like useState

**Checklist Theory:**

* Students paham why custom hooks
* Students paham naming rules
* Students paham hook composition
* Students paham return patterns

***

#### \[PHASE 2: Live Coding - 12 minutes]

**Goal:** Extract all logic from Chat.jsx to useChat custom hook

**Step 6.1: Create Custom Hook File (1 min)**

**Create:** `src/hooks/useChat.js`

**Initial structure:**

```javascript
import { useState, useEffect, useRef } from "react";

// Mock data (move from Chat.jsx)
const mockMessages = [
  { id: "m1", role: "model", content: "Halo! Aku chatbot 🙂" },
  { id: "m2", role: "user", content: "Nanti kita fokus ke hooks ya?" },
  { id: "m3", role: "model", content: "Yes. Mulai dari useState sampai custom hook." },
];

/**
 * Custom hook untuk chatbot logic
 * 
 * @returns {Object} Chat state dan functions
 */
export function useChat() {
  console.log("🪝 useChat hook called");
  
  // Logic akan dipindahkan ke sini
  
  return {
    // Return values akan ditambahkan
  };
}
```

**Explain:**

{% hint style="info" %}
"**File structure:**

* Create `hooks/` folder (convention)
* File name: `useChat.js` (match hook name)
* Named export (not default)

**JSDoc comment:**

* Documents what hook does
* What it returns
* Good practice for reusable code"
  {% endhint %}

***

**Step 6.2: Move State Logic (3 min)**

**Copy from Chat.jsx and paste into useChat:**

```javascript
export function useChat() {
  console.log("🪝 useChat hook called");
  
  // ===== STATE MANAGEMENT =====
  const [messages, setMessages] = useState(mockMessages);
  console.log("📦 Messages state:", messages.length, "messages");
  
  const [status, setStatus] = useState('idle');
  console.log("🚦 Status state:", status);
  
  const [error, setError] = useState(null);
  console.log("⚠️ Error state:", error);
  
  // ===== REF =====
  const bottomRef = useRef(null);
  
  // ... more to add
  
  return {
    messages,
    status,
    error
  };
}
```

**Explain:**

{% hint style="info" %}
"All state declarations moved. Hook can use useState just like component can.

Logs help us debug: we'll see when hook is called and what values it has."
{% endhint %}

***

**Step 6.3: Move useEffect (2 min)**

**Add to useChat:**

```javascript
// ===== SIDE EFFECTS =====
useEffect(() => {
  console.log("🎯 Auto-scroll effect triggered");
  
  const chatContainer = document.querySelector('.overflow-y-auto');
  if (chatContainer) {
    chatContainer.scrollTop = chatContainer.scrollHeight;
    console.log("✅ Scrolled to bottom");
  }
  
}, [messages.length]);
```

**Explain:**

{% hint style="info" %}
"useEffect moves into custom hook unchanged. Dependencies work the same way."
{% endhint %}

***

**Step 6.4: Move Handlers (4 min)**

**Add to useChat (before return):**

```javascript
// ===== HANDLERS =====

function sendMessage(text) {
  console.log("📤 sendMessage called:", text);
  
  if (!text.trim()) return;
  
  // Error trigger
  if (text.toLowerCase().includes('error')) {
    setStatus('error');
    setError('Simulasi error: kata "error" terdeteksi!');
    return;
  }
  
  // User message
  const userMessage = {
    id: `m${Date.now()}`,
    role: 'user',
    content: text
  };
  
  setMessages(prev => [...prev, userMessage]);
  setStatus('loading');
  setError(null);
  
  // Bot response
  setTimeout(() => {
    const botMessage = {
      id: `m${Date.now()}`,
      role: 'model',
      content: `Kamu bilang: "${text}"`
    };
    
    setMessages(prev => [...prev, botMessage]);
    setStatus('idle');
  }, 1500);
}

function clearChat() {
  console.log("🗑️ clearChat called");
  
  setMessages([]);
  setStatus('idle');
  setError(null);
}
```

**Explain:**

{% hint style="info" %}
"Handlers moved unchanged. They have access to state via closures (JavaScript feature).

Function names changed:

* `handleSend` → `sendMessage` (clearer for API)
* `handleClear` → `clearChat` (clearer for API)"
  {% endhint %}

***

**Step 6.5: Complete Return Object (1 min)**

**Update return:**

```javascript
// ===== RETURN API =====
return {
  // State values
  messages,
  status,
  error,
  
  // Functions
  sendMessage,
  clearChat,
  
  // Ref (if needed for advanced use)
  bottomRef
};
```

**Explain:**

{% hint style="info" %}
"**Return everything component needs:**

* State values (for reading)
* Functions (for actions)
* Ref (in case component needs it)

Named object = clear API. Consumer knows what each property is."
{% endhint %}

***

**Step 6.6: Update Chat.jsx to Use Hook (2 min)**

**Open Chat.jsx, REPLACE entire file with:**

```javascript
import { useChat } from "../hooks/useChat";
import ChatShell from "./ChatShell";

export default function Chat() {
  console.log("🎨 Chat component rendered");
  
  // Use custom hook (all logic abstracted!)
  const chat = useChat();
  
  // Return UI only
  return (
    <ChatShell
      messages={chat.messages}
      status={chat.status}
      error={chat.error}
      onSend={chat.sendMessage}
      onClear={chat.clearChat}
    />
  );
}
```

**Explain:**

{% hint style="success" %}
"**Chat.jsx transformation:**

**Before:**

* \~150+ lines
* State, effects, handlers, UI mixed
* Hard to read and maintain

**After:**

* \~15 lines
* Only imports and UI
* Crystal clear responsibilities

**All business logic in useChat hook:**

* \~100 lines of pure logic
* Reusable in other components
* Testable without rendering

This is **clean code architecture**!"
{% endhint %}

***

**MAJOR DEBUG CHECKPOINT:**

**Action:**

1. Save all files
2. Clear console
3. Test full flow:
   * Send message
   * See loading
   * See bot response
   * Auto-scroll works
   * Error trigger works
   * Clear works

**Expected console output:**

```
🎨 Chat component rendered
🪝 useChat hook called
📦 Messages state: 3 messages
🚦 Status state: idle
⚠️ Error state: null
🎯 Auto-scroll effect triggered
✅ Scrolled to bottom

(... send message ...)

📤 sendMessage called: test
🪝 useChat hook called  ← Re-run because state changed
...
```

**Point out:**

{% hint style="success" %}
"Everything works exactly the same! Functionality unchanged.

But structure dramatically improved:

* Component = UI only
* Hook = Logic only
* Clear separation of concerns

**This refactoring is called:**

* Extract Method pattern
* Separation of Concerns principle
* Clean Architecture

Production codebases do this all the time!"
{% endhint %}

***

#### \[PHASE 3: Compare Before/After - 2 minutes]

**Diagram: Before vs After Structure**

```
BEFORE REFACTORING:
├── Chat.jsx (200+ lines)
│   ├── State management
│   ├── Side effects
│   ├── Event handlers
│   └── UI rendering
└── (Logic not reusable)

AFTER REFACTORING:
├── hooks/useChat.js (100 lines)
│   ├── State management ✅
│   ├── Side effects ✅
│   └── Event handlers ✅
│   └── (Reusable, testable!)
│
└── components/Chat.jsx (15 lines)
    └── UI rendering only ✅
    └── (Clean, focused!)
```

**Benefits achieved:**

1. **Readability:** Chat.jsx immediately shows what UI renders
2. **Maintainability:** Logic changes in one place (hook)
3. **Reusability:** useChat can be used in other components
4. **Testability:** Can test useChat without rendering UI
5. **Scalability:** Easy to add features to hook

***

#### \[PHASE 4: Verification - 2 minutes]

**Interactive Questions:**

**Q1:** "Kenapa custom hook harus start dengan 'use'?"

**Expected answer:**

* Convention
* React recognizes it as hook
* ESLint applies hook rules

***

**Q2:** "Bisa panggil useChat di luar component?"

**Expected answer:**

* No! Hooks only in React functions
* Either component or custom hook

***

**Q3:** "useChat bisa pakai useState/useEffect?"

**Expected answer:**

* Yes! Custom hooks can call other hooks
* That's the power of composition

***

**Q4:** "Benefit utama refactoring ini apa?"

**Expected answer:**

* Separation of concerns
* Reusability
* Testability
* Cleaner code

***

**Checklist Step 6 Complete:**

* useChat.js file created
* All logic moved to useChat
* Chat.jsx cleaned up (15 lines)
* All functionality still works
* Students understand:
  * Why custom hooks
  * How to create custom hook
  * Separation of concerns
  * Clean code benefits

**Time Check:** Should be around 80 minutes from workshop start

***

## BONUS TOPICS

{% hint style="success" %}
**Optional Advanced Topics**

These sections are for extended workshops or self-study. Cover only if time permits.
{% endhint %}

***

### Bonus 1: useAutoScroll Custom Hook - Advanced Refactoring (10 min)

{% hint style="warning" %}
**IMPORTANT: This is OPTIONAL Advanced Pattern**

**In Step 4, we already implemented auto-scroll with useEffect directly in useChat. This works perfectly fine!**

This bonus section shows **how to further refactor** working code into even more reusable hooks. This is NOT required - it's an advanced pattern for when you want maximum code reuse.

**When to do this refactoring:**

* Same scroll logic needed in multiple components
* Team standardizing on reusable hook library
* Building component library or design system
* Code review asks for better separation

**When NOT to do this:**

* Auto-scroll only used once (YAGNI principle - You Ain't Gonna Need It)
* Team prefers simpler, inline code
* Early prototyping stage
  {% endhint %}

**GOAL:** Extract auto-scroll logic ke reusable custom hook (optional advanced pattern)

**THEORY REFERENCE:** Advanced custom hooks pattern - composition and reusability

***

#### Why Extract useAutoScroll?

{% hint style="info" %}
**Current situation in Step 4 (works fine!):**

```javascript
// Inside useChat.js after Step 4
const bottomRef = useRef(null);

useEffect(() => {
  bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages.length]);
```

**This code is GOOD! It works!**

**But imagine later you need:**

1. **Auto-scroll in NotificationList component**

   ```javascript
   // notifications/NotificationList.jsx
   // Need to copy-paste same scroll logic? 🤔
   ```
2. **Auto-scroll in LogViewer component**

   ```javascript
   // logs/LogViewer.jsx  
   // Copy-paste again? 🤔
   ```
3. **Auto-scroll in ActivityFeed component**

   ```javascript
   // activity/ActivityFeed.jsx
   // Copy-paste AGAIN? 😱
   ```

**Problems with copy-paste:**

* Code duplication (DRY violation)
* Bug fix needs update in 4 places
* Can't centrally configure behavior
* Hard to maintain consistency

**Solution: Extract to reusable hook!**

* Write once, use everywhere
* Fix bug in one place
* Centralized configuration
* Easier to test
  {% endhint %}

**ASK STUDENTS:**

"Jika nanti kalian punya 5 components yang perlu auto-scroll, lebih baik copy-paste 5 kali atau buat 1 reusable hook?"

***

#### Progression: Basic → Advanced

{% hint style="success" %}
**Learning Journey:**

**Step 4: Learn useEffect fundamentals**

* Focus: Understanding side effects
* Pattern: Inline useEffect in component
* Goal: Make auto-scroll work

**Bonus 1: Learn composition pattern (NOW)**

* Focus: Code reusability
* Pattern: Extract to custom hook
* Goal: Reusable across components

**Both are valid!** Choice depends on project needs.

**In this workshop:**

* Step 4 teaches useEffect (foundation)
* Bonus 1 teaches composition (advanced)
* Step 4 code works fine - no need to change if not needed
  {% endhint %}

***

#### Step 1: Create useAutoScroll Hook (3 min)

**Create:** `src/hooks/useAutoScroll.js`

```javascript
import { useEffect, useRef } from 'react';

/**
 * Custom hook untuk auto-scroll ke bottom saat content berubah
 * 
 * @param {Array} dependencies - Array of values to watch (e.g., [messages.length])
 * @param {Object} options - Scroll behavior configuration
 * @returns {React.RefObject} Ref to attach to scroll target element
 * 
 * @example
 * const bottomRef = useAutoScroll([messages.length]);
 * return <div><Messages /><div ref={bottomRef} /></div>
 */
export function useAutoScroll(dependencies = [], options = {}) {
  // Destructure options with defaults
  const {
    behavior = 'smooth',      // 'smooth' | 'instant' | 'auto'
    block = 'end',            // 'start' | 'center' | 'end' | 'nearest'
    inline = 'nearest',       // 'start' | 'center' | 'end' | 'nearest'
    enabled = true            // Enable/disable scroll
  } = options;
  
  // Create ref for scroll target
  const scrollTargetRef = useRef(null);
  
  useEffect(() => {
    // Skip if disabled
    if (!enabled) {
      console.log('⏸️ Auto-scroll disabled');
      return;
    }
    
    // Skip if ref not attached
    if (!scrollTargetRef.current) {
      console.warn('⚠️ scrollTargetRef.current is null');
      return;
    }
    
    console.log('📜 Auto-scrolling with options:', { behavior, block, inline });
    
    // Perform scroll
    scrollTargetRef.current.scrollIntoView({
      behavior,
      block,
      inline
    });
    
  }, dependencies); // Re-run when dependencies change
  
  return scrollTargetRef;
}
```

**Explain:**

{% hint style="success" %}
"**Hook design patterns:**

1. **Parameters:**
   * `dependencies` - Controls when to scroll (like useEffect deps)
   * `options` - Configuration object with defaults
2. **Return value:**
   * Single ref object (simple API)
3. **Flexible:**
   * Can configure scroll behavior
   * Can enable/disable dynamically
   * Works with any scrollable content
4. **Documentation:**
   * JSDoc comments for IDE autocomplete
   * Example usage in comment
   * Clear parameter descriptions"
     {% endhint %}

***

#### Step 2: Update useChat to Use useAutoScroll (2 min)

**Open:** `src/hooks/useChat.js`

**BEFORE:**

```javascript
import { useState, useEffect, useRef } from 'react';

export function useChat() {
  const [messages, setMessages] = useState(mockMessages);
  const bottomRef = useRef(null);
  
  // Manual scroll logic
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages.length]);
  
  // ... handlers
  
  return { messages, sendMessage, clearChat, bottomRef };
}
```

**AFTER:**

```javascript
import { useState } from 'react';
import { useAutoScroll } from './useAutoScroll';

export function useChat() {
  const [messages, setMessages] = useState(mockMessages);
  const [status, setStatus] = useState('idle');
  const [error, setError] = useState(null);
  
  // ✅ Use custom auto-scroll hook
  const bottomRef = useAutoScroll([messages.length], {
    behavior: 'smooth',
    enabled: status !== 'loading' // Don't scroll while loading
  });
  
  // ... handlers (unchanged)
  
  return { messages, status, error, sendMessage, clearChat, bottomRef };
}
```

**Explain:**

{% hint style="success" %}
"**Benefits achieved:**

1. **useChat is cleaner:**
   * No useEffect import needed
   * No useRef import needed
   * One line instead of 5
2. **Auto-scroll logic reusable:**
   * Can use in NotificationList component
   * Can use in LogViewer component
   * Can use in any scrollable content
3. **Configurable:**
   * Can disable scroll when loading
   * Can change behavior to 'instant'
   * Can add more options without changing useChat
4. **Testable:**
   * Can test useAutoScroll independently
   * Can test useChat without scroll logic
   * Separation of concerns = easier testing"
     {% endhint %}

***

#### Step 3: Advanced Usage Examples (2 min)

**Example 1: Conditional Scrolling**

```javascript
const bottomRef = useAutoScroll([messages.length], {
  // Only scroll if user is near bottom
  enabled: isUserAtBottom && !isTyping
});
```

**Example 2: Instant Scroll (No Animation)**

```javascript
const bottomRef = useAutoScroll([messages.length], {
  behavior: 'instant' // No smooth animation
});
```

**Example 3: Multiple Dependencies**

```javascript
const bottomRef = useAutoScroll([
  messages.length,
  typingIndicator,
  scrollTrigger
], {
  behavior: 'smooth'
});
```

**Example 4: Scroll Container Alternative**

```javascript
// If you want to scroll container instead of element:
export function useAutoScrollContainer(dependencies = [], options = {}) {
  const { behavior = 'smooth', enabled = true } = options;
  const containerRef = useRef(null);
  
  useEffect(() => {
    if (!enabled || !containerRef.current) return;
    
    containerRef.current.scrollTo({
      top: containerRef.current.scrollHeight,
      behavior
    });
  }, dependencies);
  
  return containerRef;
}

// Usage:
const containerRef = useAutoScrollContainer([messages.length]);

return (
  <div ref={containerRef} className="overflow-y-auto h-96">
    {messages.map(msg => <Message key={msg.id} {...msg} />)}
  </div>
);
```

***

#### Step 4: Testing the Hook (Optional - 3 min)

**Show how to test custom hooks:**

```javascript
// tests/useAutoScroll.test.js
import { renderHook } from '@testing-library/react';
import { useAutoScroll } from '../hooks/useAutoScroll';

describe('useAutoScroll', () => {
  test('returns ref object', () => {
    const { result } = renderHook(() => useAutoScroll([0]));
    
    expect(result.current).toHaveProperty('current');
    expect(result.current.current).toBeNull(); // Not attached yet
  });
  
  test('scrolls when dependencies change', () => {
    const mockScrollIntoView = jest.fn();
    
    const { rerender } = renderHook(
      ({ deps }) => useAutoScroll(deps),
      { initialProps: { deps: [0] } }
    );
    
    // Mock the ref
    const ref = { scrollIntoView: mockScrollIntoView };
    // ... attach ref and test
  });
  
  test('respects enabled option', () => {
    const { result } = renderHook(() => 
      useAutoScroll([1], { enabled: false })
    );
    
    // Scroll should not be called when disabled
  });
});
```

***

#### Verification & Discussion (2 min)

**Questions to ask students:**

1. "What's the difference between useAutoScroll and useChat?"
   * **Answer:** Single responsibility - useAutoScroll only handles scrolling
2. "Can we use useAutoScroll in other components?"
   * **Answer:** Yes! That's the whole point of custom hooks
3. "What other hooks could we extract from useChat?"
   * **Answer:** useMessages, useError, useAsyncOperation, etc.

**Point out:**

{% hint style="success" %}
"**This is composition pattern:**

* Small, focused hooks
* Combine to create complex behavior
* Reusable across application
* Easy to understand and test

**Real-world examples:**

* `useDebounce` - Debounce any value
* `useLocalStorage` - Sync with localStorage
* `useMedia` - Media query detection
* `useAsync` - Generic async operations

Large codebases have dozens of small custom hooks like this!"
{% endhint %}

***

### Bonus 2: Gemini AI Integration - Complete Guide (15 min)

**THEORY REFERENCE:** This is production-ready implementation

{% hint style="danger" %}
**IMPORTANT SECURITY NOTE:**

"Sebelum implement, pahami: **API Keys NEVER go in frontend code!**

Why? Frontend code = public. Anyone bisa inspect, steal API key, abuse quota.

Solution: Backend proxy. Frontend → Your Backend → Gemini API"
{% endhint %}

***

**Step-by-Step Implementation:**

**PART 1: Backend Proxy Setup (5 min)**

**Create backend server (Node.js + Express):**

```bash
# In project root
mkdir backend
cd backend
npm init -y
npm install express @google/generative-ai dotenv cors
```

**Create `backend/server.js`:**

```javascript
const express = require('express');
const { GoogleGenerativeAI } = require('@google/generative-ai');
const cors = require('cors');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3001;

// Middleware
app.use(cors({
  origin: 'http://localhost:5173', // Your Vite dev server
  credentials: true
}));
app.use(express.json());

// Initialize Gemini
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: 'gemini-pro' });

// Chat endpoint
app.post('/api/chat', async (req, res) => {
  try {
    const { message, history } = req.body;
    
    // Validation
    if (!message || typeof message !== 'string') {
      return res.status(400).json({ error: 'Invalid message' });
    }
    
    if (message.length > 1000) {
      return res.status(400).json({ error: 'Message too long' });
    }
    
    console.log('📥 Received message:', message);
    
    // Start chat with history
    const chat = model.startChat({
      history: history || [],
      generationConfig: {
        maxOutputTokens: 1000,
        temperature: 0.7,
      },
    });
    
    // Send message and get response
    const result = await chat.sendMessage(message);
    const response = await result.response;
    const text = response.text();
    
    console.log('📤 Sending response:', text.substring(0, 50) + '...');
    
    res.json({ 
      reply: text,
      success: true 
    });
    
  } catch (error) {
    console.error('❌ Error:', error);
    
    // Handle specific errors
    if (error.message.includes('API key')) {
      return res.status(500).json({ 
        error: 'API configuration error' 
      });
    }
    
    if (error.message.includes('quota')) {
      return res.status(429).json({ 
        error: 'Rate limit exceeded. Please try again later.' 
      });
    }
    
    res.status(500).json({ 
      error: 'Failed to generate response' 
    });
  }
});

// Health check
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

app.listen(PORT, () => {
  console.log(`🚀 Backend server running on http://localhost:${PORT}`);
  console.log(`✅ CORS enabled for: http://localhost:5173`);
});
```

**Create `backend/.env`:**

```bash
GEMINI_API_KEY=your_api_key_here
PORT=3001
```

**Explain to students:**

{% hint style="info" %}
"**Backend proxy pattern:**

1. Frontend sends request to OUR backend (localhost:3001)
2. Backend calls Gemini API with API key from .env
3. Backend returns response to frontend

**Security layers:**

* API key in .env (never committed to git)
* CORS limits which origins can call API
* Input validation prevents abuse
* Error handling doesn't leak sensitive info

**Add to .gitignore:**

```
backend/.env
backend/node_modules/
```

{% endhint %}

***

**PART 2: Frontend Integration (5 min)**

**Update `src/hooks/useChat.js`:**

```javascript
import { useState, useEffect } from 'react';

const BACKEND_URL = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3001';

export function useChat() {
  const [messages, setMessages] = useState([]);
  const [status, setStatus] = useState('idle');
  const [error, setError] = useState(null);
  
  // Convert messages to Gemini history format
  const getHistory = () => {
    return messages.map(msg => ({
      role: msg.role === 'user' ? 'user' : 'model',
      parts: [{ text: msg.content }]
    }));
  };
  
  async function sendMessage(text) {
    if (!text.trim()) return;
    
    // User message
    const userMessage = {
      id: `m${Date.now()}`,
      role: 'user',
      content: text
    };
    
    setMessages(prev => [...prev, userMessage]);
    setStatus('loading');
    setError(null);
    
    try {
      console.log('🌐 Calling backend API...');
      
      // Call backend proxy
      const response = await fetch(`${BACKEND_URL}/api/chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message: text,
          history: getHistory()
        })
      });
      
      console.log('📡 Response status:', response.status);
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Network error');
      }
      
      const data = await response.json();
      console.log('✅ Received response from API');
      
      // Bot message
      const botMessage = {
        id: `m${Date.now() + 1}`,
        role: 'model',
        content: data.reply
      };
      
      setMessages(prev => [...prev, botMessage]);
      setStatus('idle');
      
    } catch (err) {
      console.error('❌ Error:', err);
      
      setStatus('error');
      setError(
        err.message || 
        'Failed to send message. Please check your connection.'
      );
      
      // Remove user message on error (optional)
      // setMessages(prev => prev.slice(0, -1));
    }
  }
  
  function clearChat() {
    setMessages([]);
    setStatus('idle');
    setError(null);
  }
  
  return {
    messages,
    status,
    error,
    sendMessage,
    clearChat
  };
}
```

**Create `frontend/.env`:**

```bash
VITE_BACKEND_URL=http://localhost:3001
```

**Explain:**

{% hint style="info" %}
"**Frontend changes:**

1. Replace setTimeout with real fetch call
2. Call backend proxy, not Gemini directly
3. Send conversation history (for context)
4. Handle network errors properly
5. Better error messages for users

**Environment variables:**

* VITE\_BACKEND\_URL can change per environment
* Development: localhost:3001
* Production: <https://your-backend.com>
* Vite exposes VITE\_\* variables to frontend"
  {% endhint %}

***

**PART 3: Testing (5 min)**

**Terminal 1 - Start Backend:**

```bash
cd backend
node server.js
# Should see: 🚀 Backend server running on http://localhost:3001
```

**Terminal 2 - Start Frontend:**

```bash
npm run dev
# Should see: Local: http://localhost:5173/
```

**Test flow:**

1. Open browser → <http://localhost:5173>
2. Type message: "Explain React hooks in simple terms"
3. Watch console logs:

**Frontend console:**

```
🌐 Calling backend API...
📡 Response status: 200
✅ Received response from API
```

**Backend terminal:**

```
📥 Received message: Explain React hooks in simple terms
📤 Sending response: React hooks are functions that let you...
```

4. See real Gemini response in UI
5. Test conversation continuity (ask follow-up)
6. Test error handling (stop backend, try send)

**Explain:**

{% hint style="success" %}
"**What we achieved:**

* Real AI responses
* Conversation context maintained
* Secure (API key protected)
* Error handling
* Production-ready pattern

**For deployment:**

* Backend: Deploy to Railway, Render, or AWS
* Frontend: Deploy to Vercel, Netlify
* Update VITE\_BACKEND\_URL to production URL
* Add rate limiting (express-rate-limit)
* Add authentication if needed"
  {% endhint %}

***

**Common Issues & Solutions:**

**Issue 1: CORS Error**

```
Access to fetch at 'http://localhost:3001' from origin 'http://localhost:5173' 
has been blocked by CORS policy
```

**Solution:**

```javascript
// In server.js, check CORS config
app.use(cors({
  origin: 'http://localhost:5173', // Must match frontend URL
  credentials: true
}));
```

**Issue 2: API Key Error**

```
❌ Error: API key not valid
```

**Solution:**

* Check .env file exists in backend/
* Check key format: `GEMINI_API_KEY=AIza...`
* Restart backend server (dotenv loads on startup)
* Get new key from <https://ai.google.dev/>

**Issue 3: Connection Refused**

```
Failed to fetch: net::ERR_CONNECTION_REFUSED
```

**Solution:**

* Check backend is running (Terminal 1)
* Check port 3001 not blocked
* Check VITE\_BACKEND\_URL matches backend PORT

***

**Production Checklist:**

* API keys in environment variables (never in code)
* .env files in .gitignore
* CORS properly configured
* Input validation (length, type, sanitization)
* Rate limiting (prevent abuse)
* Error handling (don't leak sensitive info)
* Logging (for debugging and monitoring)
* Health check endpoint (for deployment monitoring)
* HTTPS in production
* Environment-specific configs (dev, staging, prod)

***

## TIME MANAGEMENT & FLEXIBILITY GUIDE

{% hint style="info" %}
**For Instructors Only**

Use this guide to adapt the workshop to different time constraints and audience levels.
{% endhint %}

***

### Workshop Duration Options

#### EXPRESS (60 minutes)

* Target: Experienced developers, already know JavaScript
* Goal: Quick hooks overview

**What to KEEP:**

* Step 1: useState (basic only, 8 min)
* Step 2: Handlers (skip functional updates theory, 10 min)
* Step 4: useEffect (basic only, 8 min)
* Step 6: Custom hooks (show final result, 10 min)
* Key debugging checkpoints only

**What to SKIP:**

* Detailed theory explanations (point to THEORY.md)
* Step 3: Error handling (optional pattern)
* Step 5: useRef (can be homework)
* Interactive Q\&A (save for end)
* Bonus topics

**Pacing Schedule:**

```
0-5 min:   Intro + setup check
5-15 min:  useState basic
15-25 min: Event handlers
25-35 min: useEffect basic
35-50 min: Custom hooks demo
50-60 min: Q&A + wrap-up
```

***

#### STANDARD (90 minutes) - Recommended

* Target: Students with basic JS knowledge
* Goal: Solid understanding with practice
* Full flow as written in main guide

***

#### EXTENDED (120 minutes)

* Target: Beginners or hands-on workshop
* Goal: Deep understanding + practice time

**What to ADD:**

* More practice exercises between steps
* Live debugging demonstrations (intentional errors)
* Bonus: Gemini API integration demo
* More interactive Q\&A throughout
* Code review of student attempts

**Pacing Schedule:**

```
0-10 min:   Intro + setup
10-30 min:  useState (extended theory + practice)
30-50 min:  Event handlers + async
50-60 min:  Error handling + break
60-75 min:  useEffect + useRef
75-100 min: Custom hooks (live refactoring)
100-115 min: Bonus (API integration or optimization)
115-120 min: Wrap-up
```

***

### What Debug Steps Can Be Skipped?

**Debug checkpoints are tiered by importance:**

#### CRITICAL (Never skip)

1. **Step 1 Checkpoint 2:** Messages state initialization
   * WHY: Proves useState works, shows initial value
   * TIME: 30 seconds
2. **Step 2 Major Checkpoint:** Full send message flow
   * WHY: Shows re-renders, async flow, state updates
   * TIME: 2 minutes
3. **Step 4 Checkpoint:** useEffect timing
   * WHY: Proves effect runs after render (key concept)
   * TIME: 1 minute

#### IMPORTANT (Skip if time is tight)

4. **Step 1 Checkpoint 1:** Render tracker
   * Can mention concept without detailed demo
   * Students can verify on their own
5. **Step 2 Checkpoints 1-3:** Individual state updates
   * If confident students understand, combine into one check
6. **Step 5 Checkpoint:** Ref initialization
   * Can skip if scrolling works (effect is visible)

#### OPTIONAL (Skip in express mode)

7. **All error handling debug steps**
   * Error handling is bonus pattern
   * Can demo without detailed console walkthrough
8. **Step 6 debug checkpoint**
   * If refactoring works, detailed logs not critical
   * Students can verify UI works

***

### What Theory Can Be Shortened?

**THEORY TIERS:**

**Tier 1: Core (Must explain)**

* What is state? Why useState?
* State triggers re-render
* useEffect runs after render
* Why custom hooks?

**Tier 2: Important (Shorten if needed)**

* Immutable updates (show quick example, skip detailed patterns table)
* Functional updates (mention concept, skip stale closure deep dive)
* useEffect dependencies (show pattern, skip all edge cases)
* Ref vs state (quick comparison, skip use cases table)

**Tier 3: Optional (Skip if needed)**

* State machine pattern (nice to have, not critical)
* Lazy initialization (advanced optimization)
* useCallback/useMemo (mention in bonus only)
* All "Why not..." comparisons (point to THEORY.md)

***

### Audience-Specific Adjustments

**For BEGINNERS (new to React)**

* Slow down theory explanations
* Use more analogies (kotak penyimpanan, renovasi rumah)
* Do all debug checkpoints (builds confidence)
* Encourage questions frequently
* Skip bonus topics entirely
* Extend Step 1 (useState) to 20 minutes

**For INTERMEDIATE (know React basics)**

* Standard pace
* Balance theory and practice
* Do key debug checkpoints
* Interactive Q\&A
* Include one bonus topic (custom hooks extra)

**For ADVANCED (experienced React devs)**

* Fast pace
* Skip basic theory (point to docs)
* Focus on patterns and best practices
* Challenge with optimization questions
* Include production Q\&A
* Show Gemini API integration
* Discuss testing strategies

***

### Emergency Time Savers

**If running behind schedule:**

1. **Skip live typing, show completed code:**
   * Instead of typing line by line, show finished code
   * Explain what each part does
   * TIME SAVED: \~30% per section
2. **Use solution file:**
   * Open Chat.solution.jsx
   * Walk through key parts
   * Students follow along
   * TIME SAVED: 15-20 minutes
3. **Skip error handling (Step 3):**
   * Not critical for hooks understanding
   * Can be homework
   * TIME SAVED: 8 minutes
4. **Combine useEffect + useRef (Steps 4-5):**
   * Show useEffect with direct DOM query (no ref)
   * Skip useRef theory
   * TIME SAVED: 5 minutes
5. **Demo custom hooks only:**
   * Show before/after comparison
   * Skip live refactoring
   * TIME SAVED: 10 minutes
6. **Reduce Q\&A time:**
   * Parking lot technique ("Great question, let's discuss after")
   * Answer async via chat/email
   * TIME SAVED: Variable

***

### What Students Can Do Independently

**Point students to these for self-study:**

**Can learn on their own (low difficulty):**

* Error handling pattern (Step 3) - clear example in code
* useRef for DOM (Step 5) - straightforward concept
* Additional useState patterns (THEORY.md)
* Component structure (file organization)

**Need guidance (medium difficulty):**

* useEffect dependencies - common confusion, answer questions
* Functional updates - stale closure can be tricky
* Custom hooks - need to see value
* Async state management - timing issues

**Should cover in workshop (high difficulty):**

* When to use useState vs useRef vs props
* Why immutable updates (reference equality)
* useEffect timing and lifecycle
* Separating concerns (why custom hooks)

***

### Quick Decision Matrix

**Use this during workshop to decide on-the-fly:**

```
Am I running behind?
├─ Yes
│  ├─ How much? < 5 min
│  │  └─ Skip next optional debug checkpoint
│  ├─ How much? 5-10 min
│  │  └─ Shorten next theory section
│  └─ How much? > 10 min
│     └─ Skip Step 3 entirely + reduce Q&A
│
└─ No
   └─ Are students engaged?
      ├─ Yes, asking questions
      │  └─ Take extra time, reduce bonus section
      └─ No, looking confused
         └─ Slow down, add more examples
```

***

### Key Insight for Instructors

{% hint style="success" %}
**BETTER to finish fewer topics WELL than rush through all topics poorly.**

If students truly understand:

* useState (state concept + immutability)
* useEffect (side effects + dependencies)
* Why custom hooks (separation of concerns)

They can learn the rest on their own. Foundation matters most!
{% endhint %}

***

## FINAL NOTES FOR INSTRUCTOR

{% hint style="success" %}
**Post-Workshop Reflection**

Use this section to evaluate workshop effectiveness and plan improvements.
{% endhint %}

***

### What Went Well Checklist

* Students engaged throughout
* Questions answered clearly
* All debugging checkpoints hit
* Time management good
* Code worked as expected
* Theory connected to practice

### Common Student Struggles

* Initial state concept (need more analogies)
* Functional updates (show more examples)
* useEffect dependencies (draw more diagrams)
* Async timing (slow down explanation)
* Custom hook benefits (show more comparisons)

### Improvements for Next Time

* More visual diagrams
* More interactive polls/questions
* Shorter code blocks (break down more)
* More debugging demonstrations
* Better time buffers

### Personal Reminders

* Breathe, don't rush
* Check student understanding frequently
* Use analogies liberally
* Show enthusiasm - it's contagious!
* Mistakes are OK - they're learning moments
* Every question is valid

***

**END OF DETAILED INSTRUCTOR NOTES**

{% hint style="success" %}
**Remember:** Your goal is not just to teach syntax, but to inspire understanding and curiosity. Make them think "Oh, NOW I get it!" not just "I can copy this code."

**Good luck! You've got this!** 🚀
{% endhint %}

***

### Pagination

* **Previous:** [THEORY](https://personal-space-4.gitbook.io/complete-guide/theory.md)
* **Top:** [Quick Navigation](#quick-navigation)
