> 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-5-useref-dom-references.md). Agents can also search and read this documentation through its [MCP server](https://personal-space-4.gitbook.io/complete-guide/~gitbook/mcp).

# Step 5 — useRef (DOM References)

useRef untuk DOM + implement auto-scroll.

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

***
