> 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/detailed-live-coding-script/step-6-custom-hook-refactoring.md). Agents can also search and read this documentation through its [MCP server](https://personal-space-4.gitbook.io/complete-guide/~gitbook/mcp).

# Step 6 — Custom Hook Refactoring

Ekstrak logic ke custom hook useChat.

{% 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 %}

***

## 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

***
