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

# THEORY

Dokumen ini memberikan penjelasan teoritis mendalam tentang React Hooks untuk melengkapi pembelajaran praktis di project ini.

***

## Daftar Isi

{% hint style="info" %}
**Comprehensive React Hooks Guide**

This document covers fundamental concepts and modern ecosystem integration.
{% endhint %}

**Core Concepts:**

1. [Apa itu React Hooks?](#apa-itu-react-hooks)
2. [Mengapa Hooks Diciptakan?](#mengapa-hooks-diciptakan)
3. [Rules of Hooks](#rules-of-hooks)
4. [useState - State Management](#usestate---state-management)
5. [useEffect - Side Effects](#useeffect---side-effects)
6. [useRef - Mutable References](#useref---mutable-references)
7. [Custom Hooks - Reusable Logic](#custom-hooks---reusable-logic)
8. [State vs Props vs Ref](#state-vs-props-vs-ref)
9. [Common Patterns](#common-patterns)
10. [Anti-Patterns to Avoid](#anti-patterns-to-avoid)
11. [Mental Models](#mental-models)

**Modern Ecosystem:**

12. [Modern React Ecosystem & Hooks](#modern-react-ecosystem--hooks)
    * [State Management: Context API, Zustand, Redux Toolkit](#state-management-libraries)
    * [Data Fetching: Fetch, Axios, TanStack Query](#data-fetching-libraries)
    * [Form Validation: Zod, React Hook Form](#form-validation-libraries)
    * [Next.js Integration](#nextjs-integration-dengan-hooks)
    * [Library Comparison & Decision Making](#library-comparison--decision-making)

***

## Apa itu React Hooks?

{% hint style="success" %}
**Foundation Section**

Understand what React Hooks are and why they exist.
{% endhint %}

### Definisi

**Hooks** adalah fungsi spesial yang memungkinkan kita "hook into" React features (state, lifecycle, context, dll) dari **function components**.

Sebelum Hooks (React < 16.8):

* Function components = stateless, "dumb" components
* Class components = stateful, "smart" components dengan lifecycle

Setelah Hooks (React >= 16.8):

* Function components bisa punya state dan lifecycle
* Class components masih supported, tapi tidak recommended untuk code baru

### Kenapa Disebut "Hooks"?

Analogi: seperti "hook" (kait) yang kamu tempelkan ke sistem React untuk:

* Hook into state management (`useState`)
* Hook into lifecycle (`useEffect`)
* Hook into context (`useContext`)
* Hook into ref system (`useRef`)

```javascript
// "Mengaitkan" state ke component
const [count, setCount] = useState(0);

// "Mengaitkan" effect ke component lifecycle
useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]);
```

***

## Mengapa Hooks Diciptakan?

{% hint style="info" %}
**Historical Context**

Learn about the problems Hooks solve and why React team created them.
{% endhint %}

### Problem dengan Class Components

#### 1. **Complex Components Sulit Dipahami**

Class components dengan banyak lifecycle methods jadi complex:

```javascript
class ChatComponent extends React.Component {
  componentDidMount() {
    // Setup subscriptions
    // Fetch data
    // Add event listeners
  }

  componentDidUpdate(prevProps) {
    // Update subscriptions
    // Fetch new data if props changed
  }

  componentWillUnmount() {
    // Cleanup subscriptions
    // Remove event listeners
  }

  render() { /* ... */ }
}
```

**Problem:** Related logic scattered across multiple lifecycle methods.

#### 2. **Sulit Reuse Stateful Logic**

Sebelum Hooks, reuse logic perlu:

* Higher-Order Components (HOC) → wrapper hell
* Render Props → callback hell

```javascript
<DataFetcher>
  {data => (
    <ThemeProvider>
      {theme => (
        <UserContext.Consumer>
          {user => (
            // Finally render your UI here!
          )}
        </UserContext.Consumer>
      )}
    </ThemeProvider>
  )}
</DataFetcher>
```

#### 3. **Classes Confusing**

```javascript
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.handleClick = this.handleClick.bind(this); // ← Confusing!
  }

  handleClick() {
    this.setState({ count: this.state.count + 1 }); // `this` issues
  }

  render() {
    return <button onClick={this.handleClick}>{this.state.count}</button>;
  }
}
```

**Problems:**

* `this` keyword confusing (especially untuk beginners)
* Need to bind methods
* Minifier tidak optimize class methods dengan baik

### Solusi: Hooks

```javascript
function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
```

**Benefits:**

* No `this`
* No binding
* Related logic grouped together
* Easy to extract and reuse (custom hooks)

***

## Rules of Hooks

{% hint style="danger" %}
**Critical Rules - Must Follow**

These rules are enforced by ESLint and breaking them causes bugs.
{% endhint %}

### Rule 1: Only Call Hooks at the Top Level

**❌ JANGAN:**

```javascript
function Counter() {
  if (condition) {
    const [count, setCount] = useState(0); // ❌ Conditional hook
  }

  for (let i = 0; i < 10; i++) {
    useEffect(() => {...}); // ❌ Hook in loop
  }

  function nested() {
    const [state, setState] = useState(0); // ❌ Hook in nested function
  }
}
```

**✅ LAKUKAN:**

```javascript
function Counter() {
  const [count, setCount] = useState(0);           // ✅ Top-level
  const [enabled, setEnabled] = useState(false);   // ✅ Top-level
  
  useEffect(() => {
    if (enabled) {
      // Condition INSIDE effect - OK!
    }
  }, [enabled]);

  // Use state values in conditional logic - OK!
  if (count > 10) {
    return <div>Too high!</div>;
  }

  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
```

### Rule 2: Only Call Hooks from React Functions

**✅ Boleh dipanggil dari:**

* Function components
* Custom hooks

**❌ Jangan dipanggil dari:**

* Regular JavaScript functions
* Class components
* Event handlers (tapi boleh panggil setState dari hooks yang sudah declared)

```javascript
// ❌ SALAH
function regularFunction() {
  const [state, setState] = useState(0); // ❌ Not a React function
}

// ✅ BENAR
function MyComponent() {
  const [state, setState] = useState(0); // ✅ Function component
}

// ✅ BENAR
function useCustomHook() {
  const [state, setState] = useState(0); // ✅ Custom hook (prefix 'use')
}
```

### Kenapa Rules Ini Penting?

React relies on **hook call order** untuk track state antar renders.

**Internal React mechanism (simplified):**

```javascript
// First render
useState(0)    // Hook 1 → state[0]
useState('')   // Hook 2 → state[1]
useEffect(...) // Hook 3 → effects[0]

// Second render (harus urutan yang sama!)
useState(0)    // Hook 1 → state[0] ✅
useState('')   // Hook 2 → state[1] ✅
useEffect(...) // Hook 3 → effects[0] ✅
```

Jika order berubah (karena conditional/loop), React tidak tahu state mana yang belong to hook mana:

```javascript
// First render
if (true) useState(0);  // Hook 1 → state[0]
useState('');           // Hook 2 → state[1]

// Second render (if becomes false)
// useState(0) SKIP!    // Hook 1 tidak dipanggil
useState('');           // Hook 1 → state[0] ❌ Wrong mapping!
```

***

## useState - State Management

{% hint style="info" %}
**Most Common Hook**

Master useState for managing component state.
{% endhint %}

### Konsep Fundamental

**State** adalah data yang:

1. **Belongs to component** (bukan global)
2. **Can change over time** (dari user action, API, timer, dll)
3. **Triggers re-render when updated** (agar UI sync dengan data)

### Sintaks

```javascript
const [currentValue, setterFunction] = useState(initialValue);
```

**Breakdown:**

* `currentValue`: State saat ini (immutable, read-only)
* `setterFunction`: Function untuk update state (trigger re-render)
* `initialValue`: Nilai awal (hanya dipakai saat first render)

### Cara Kerja Internal (Simplified)

```javascript
// Pseudo-code React internal
let hookIndex = 0;
let componentState = [];

function useState(initialValue) {
  const currentIndex = hookIndex;
  
  // Initialize state jika belum ada
  if (componentState[currentIndex] === undefined) {
    componentState[currentIndex] = initialValue;
  }

  const currentValue = componentState[currentIndex];
  
  const setState = (newValue) => {
    // Update state
    if (typeof newValue === 'function') {
      componentState[currentIndex] = newValue(componentState[currentIndex]);
    } else {
      componentState[currentIndex] = newValue;
    }
    
    // Schedule re-render
    scheduleRender();
  };

  hookIndex++; // Move to next hook position
  return [currentValue, setState];
}
```

### Immutable Updates

**Kenapa state harus immutable?**

React compare state dengan **reference equality** (===):

```javascript
const oldState = [1, 2, 3];
oldState.push(4);              // Mutasi - reference tidak berubah
setState(oldState);             // React: oldState === oldState → NO RE-RENDER ❌

const newState = [...oldState, 4]; // New array - reference berubah
setState(newState);                // React: oldState !== newState → RE-RENDER ✅
```

**Immutable update patterns:**

```javascript
// Array
const [items, setItems] = useState([1, 2, 3]);

// Add item
setItems([...items, 4]);              // ✅
setItems(prev => [...prev, 4]);       // ✅ Better (functional)

// Remove item
setItems(items.filter(x => x !== 2)); // ✅
setItems(prev => prev.filter(x => x !== 2)); // ✅ Better

// Update item
setItems(items.map(x => x === 2 ? 20 : x)); // ✅

// Object
const [user, setUser] = useState({ name: 'John', age: 30 });

// Update property
setUser({ ...user, age: 31 });       // ✅
setUser(prev => ({ ...prev, age: 31 })); // ✅ Better

// Nested object
setUser({
  ...user,
  address: { ...user.address, city: 'Jakarta' }
}); // ✅
```

### Functional Updates

**Kenapa pakai functional update?**

```javascript
// ❌ Problem: Stale closure
function handleClick() {
  setCount(count + 1); // count = 0
  setCount(count + 1); // count masih 0! (stale)
  // Result: count = 1 (bukan 2!)
}

// ✅ Solution: Functional update
function handleClick() {
  setCount(prev => prev + 1); // prev = 0 → result 1
  setCount(prev => prev + 1); // prev = 1 → result 2
  // Result: count = 2 ✅
}
```

**Kapan pakai functional update?**

* New state bergantung pada previous state
* Di dalam async functions/callbacks
* Multiple updates dalam satu event
* Di dalam useEffect/useCallback dengan dependencies

### Lazy Initialization

**Problem: Expensive initial calculation**

```javascript
// ❌ Function jalan setiap render (boros!)
const [data, setData] = useState(expensiveComputation());
```

**Solution: Lazy initializer**

```javascript
// ✅ Function hanya jalan sekali saat mount
const [data, setData] = useState(() => expensiveComputation());

// Example
const [messages, setMessages] = useState(() => {
  // Read from localStorage (expensive I/O)
  const saved = localStorage.getItem('messages');
  return saved ? JSON.parse(saved) : [];
});
```

**Kapan pakai?**

* Initial value dari localStorage/sessionStorage
* Complex computation
* Initial value dari props (jika props tidak berubah)

***

## useEffect - Side Effects

{% hint style="info" %}
**Lifecycle Hook**

Handle side effects and lifecycle events in function components.
{% endhint %}

### Apa itu Side Effect?

**Side effect** adalah operasi yang:

1. Terjadi **setelah render** (bukan during render)
2. **Mempengaruhi dunia luar** (DOM, network, subscriptions, dll)
3. **Tidak murni** (not pure)

**Examples:**

* DOM manipulation (scroll, focus, measure)
* Data fetching (API calls)
* Subscriptions (WebSocket, event listeners)
* Timers (setTimeout, setInterval)
* Logging, analytics

### Kenapa Render Harus Pure?

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

**Problems:**

* React bisa render multiple times (strict mode render 2x)
* Render bisa di-cancel (Suspense, Concurrent Rendering)
* Render bisa di-retry (error recovery)
* Side effect dalam render = unpredictable behavior

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

### Sintaks

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

**Parts:**

1. **Effect function**: Jalan setelah render commit ke DOM
2. **Cleanup function** (optional): Jalan sebelum effect berikutnya atau component unmount
3. **Dependencies array** (optional): Mengontrol kapan effect re-run

### Dependencies Array Patterns

#### 1. No Dependencies Array

```javascript
useEffect(() => {
  console.log('Every render!');
}); // ⚠️ Runs after EVERY render (usually not what you want)
```

**Use case:** Jarang dipakai. Mungkin untuk logging/debugging.

#### 2. Empty Dependencies `[]`

```javascript
useEffect(() => {
  console.log('Once on mount!');
  
  return () => {
    console.log('Once on unmount!');
  };
}, []); // ✅ Runs once on mount, cleanup on unmount
```

**Use case:**

* Fetch data saat component mount
* Setup global listeners
* Initialize analytics

#### 3. Specific Dependencies

```javascript
useEffect(() => {
  console.log('When count changes!');
}, [count]); // ✅ Re-run when count changes
```

**Use case:**

* Sync with external system based on state/props
* Re-fetch data when ID changes
* Update document title when state changes

### Dependency Rules

**ESLint rule:** `react-hooks/exhaustive-deps`

**Principle:** Include ALL values used inside effect that could change.

```javascript
function Chat({ userId }) {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    // Uses: userId, messages
    console.log(`User ${userId} has ${messages.length} messages`);
  }, [userId, messages]); // ✅ Include both
}
```

**Exceptions:**

* setState functions (stable, no need to include)
* ref.current (mutable, bukan reactive)
* Functions/values defined outside component (tidak akan berubah)

```javascript
const CONSTANT = 10; // Outside component

function Component() {
  const [count, setCount] = useState(0);
  const ref = useRef();

  useEffect(() => {
    console.log(CONSTANT);  // No need in deps (constant)
    console.log(ref.current); // No need in deps (mutable)
    setCount(c => c + 1);    // No need in deps (stable)
  }, []); // ✅ Empty deps OK
}
```

### Cleanup Pattern

**Kenapa butuh cleanup?**

Untuk avoid **memory leaks** dan **stale subscriptions**.

```javascript
useEffect(() => {
  // Setup: Subscribe to something
  const subscription = api.subscribe(userId, (data) => {
    setData(data);
  });

  // Cleanup: Unsubscribe when:
  // 1. Component unmounts
  // 2. userId changes (before running new effect)
  return () => {
    subscription.unsubscribe();
  };
}, [userId]);
```

**Lifecycle:**

```
Mount → Effect runs
       ↓
Update (userId changes) → Cleanup runs → New effect runs
       ↓
Unmount → Cleanup runs
```

**Common cleanup scenarios:**

```javascript
// Event listeners
useEffect(() => {
  const handler = (e) => console.log(e);
  window.addEventListener('resize', handler);
  
  return () => window.removeEventListener('resize', handler);
}, []);

// Timers
useEffect(() => {
  const timer = setTimeout(() => console.log('Hi'), 1000);
  
  return () => clearTimeout(timer);
}, []);

// Intervals
useEffect(() => {
  const interval = setInterval(() => console.log('Tick'), 1000);
  
  return () => clearInterval(interval);
}, []);

// Fetch (AbortController)
useEffect(() => {
  const controller = new AbortController();
  
  fetch('/api/data', { signal: controller.signal })
    .then(res => res.json())
    .then(data => setData(data))
    .catch(err => {
      if (err.name !== 'AbortError') console.error(err);
    });
  
  return () => controller.abort();
}, []);
```

### Common Pitfalls

#### 1. Infinite Loop

```javascript
// ❌ INFINITE LOOP
useEffect(() => {
  setCount(count + 1); // Trigger re-render → effect runs → trigger re-render → ...
}); // No dependencies = runs every render!

// ❌ INFINITE LOOP (subtle)
useEffect(() => {
  setData([...data, 'new']); // data berubah → trigger effect → data berubah → ...
}, [data]); // data in deps!

// ✅ FIX: Add specific condition
useEffect(() => {
  if (data.length < 10) {
    setData([...data, 'new']);
  }
}, [data]);

// ✅ BETTER: Don't include data in deps if updating it
useEffect(() => {
  setData(prev => [...prev, 'new']); // Functional update
}, []); // Run once
```

#### 2. Missing Dependencies

```javascript
// ❌ ESLint warning
useEffect(() => {
  console.log(count); // Uses count
}, []); // Missing count in deps!

// ✅ FIX
useEffect(() => {
  console.log(count);
}, [count]); // Include count
```

#### 3. Object/Array Dependencies

```javascript
// ❌ Runs every render (new object reference every time)
const options = { userId, limit: 10 };
useEffect(() => {
  fetch('/api/data', options);
}, [options]); // options is new object every render!

// ✅ FIX: Use primitive dependencies
useEffect(() => {
  const options = { userId, limit: 10 }; // Create inside effect
  fetch('/api/data', options);
}, [userId]); // Only re-run when userId changes

// ✅ ALTERNATIVE: useMemo
const options = useMemo(() => ({ userId, limit: 10 }), [userId]);
useEffect(() => {
  fetch('/api/data', options);
}, [options]); // Stable reference (unless userId changes)
```

***

## useRef - Mutable References

{% hint style="info" %}
**Mutable Container**

Store mutable values that don't trigger re-renders.
{% endhint %}

### Konsep Fundamental

**Ref** adalah container untuk mutable value yang:

1. **Persist across renders** (seperti state)
2. **Tidak trigger re-render when updated** (berbeda dari state)
3. **Mutable** (bisa ubah .current langsung)

### Sintaks

```javascript
const ref = useRef(initialValue);

// Access
console.log(ref.current);

// Update (tidak trigger re-render!)
ref.current = newValue;
```

### Use Cases

#### 1. DOM References

```javascript
function TextInput() {
  const inputRef = useRef(null);

  const focusInput = () => {
    inputRef.current?.focus(); // DOM method
  };

  return (
    <>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus</button>
    </>
  );
}
```

**Common DOM operations:**

* `ref.current.focus()` - Focus element
* `ref.current.scrollIntoView()` - Scroll to element
* `ref.current.getBoundingClientRect()` - Get element dimensions
* `ref.current.value` - Get input value (uncontrolled)

#### 2. Storing Timer IDs

```javascript
function Timer() {
  const [count, setCount] = useState(0);
  const intervalRef = useRef(null);

  const startTimer = () => {
    intervalRef.current = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
  };

  const stopTimer = () => {
    clearInterval(intervalRef.current);
  };

  useEffect(() => {
    return () => clearInterval(intervalRef.current); // Cleanup
  }, []);

  return (
    <>
      <div>{count}</div>
      <button onClick={startTimer}>Start</button>
      <button onClick={stopTimer}>Stop</button>
    </>
  );
}
```

#### 3. Storing Previous Values

```javascript
function Counter() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef();

  useEffect(() => {
    prevCountRef.current = count; // Save current value for next render
  });

  const prevCount = prevCountRef.current; // Previous render's value

  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {prevCount}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
```

#### 4. Storing Instances

```javascript
function WebSocketComponent() {
  const wsRef = useRef(null);

  useEffect(() => {
    // Create WebSocket instance
    wsRef.current = new WebSocket('ws://localhost:8080');
    
    wsRef.current.onmessage = (event) => {
      console.log('Message:', event.data);
    };

    // Cleanup
    return () => {
      wsRef.current?.close();
    };
  }, []);

  const sendMessage = (msg) => {
    wsRef.current?.send(msg);
  };

  return <button onClick={() => sendMessage('Hello')}>Send</button>;
}
```

### State vs Ref Comparison

| Aspek                  | useState             | useRef                   |
| ---------------------- | -------------------- | ------------------------ |
| **Initial value**      | `useState(initial)`  | `useRef(initial)`        |
| **Current value**      | `state`              | `ref.current`            |
| **Update**             | `setState(newValue)` | `ref.current = newValue` |
| **Trigger re-render?** | ✅ Ya                 | ❌ Tidak                  |
| **Mutability**         | Immutable            | Mutable                  |
| **When to use**        | UI data yang berubah | Non-UI persistent data   |

**Example comparison:**

```javascript
function ComparisonExample() {
  // State: Trigger re-render
  const [count, setCount] = useState(0);
  
  // Ref: No re-render
  const renderCountRef = useRef(0);

  // Increment render count (setiap render)
  renderCountRef.current = renderCountRef.current + 1;

  return (
    <div>
      <p>Count (state): {count}</p>
      <p>Render count (ref): {renderCountRef.current}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment Count (will re-render)
      </button>
      <button onClick={() => renderCountRef.current++}>
        Increment Ref (NO re-render) - won't see change until next render!
      </button>
    </div>
  );
}
```

### Callback Ref Pattern

Alternative to useRef: function as ref.

```javascript
function MeasureElement() {
  const [height, setHeight] = useState(0);

  // Callback ref
  const measureRef = (node) => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);
    }
  };

  return (
    <>
      <div ref={measureRef}>
        <p>This element's height is {height}px</p>
      </div>
    </>
  );
}
```

**When to use callback ref:**

* Need to measure element on mount/change
* Ref attached to conditional element
* Need to react to ref changes

***

## Custom Hooks - Reusable Logic

{% hint style="success" %}
**Code Reusability**

Create custom hooks to share logic between components.
{% endhint %}

### Apa itu Custom Hook?

**Custom hook** adalah JavaScript function yang:

1. **Name starts with "use"** (convention)
2. **Can call other hooks** (useState, useEffect, dll)
3. **Returns data/functions** untuk digunakan components
4. **Encapsulates reusable logic**

### Kenapa Buat Custom Hook?

**Before custom hooks:**

```javascript
// Component A
function ComponentA() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  
  useEffect(() => {
    setLoading(true);
    fetch('/api/data').then(/* ... */);
  }, []);
  
  // ... render logic
}

// Component B (duplicate logic!)
function ComponentB() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  
  useEffect(() => {
    setLoading(true);
    fetch('/api/data').then(/* ... */);
  }, []);
  
  // ... render logic
}
```

**After custom hooks:**

```javascript
// Custom hook (reusable)
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  
  useEffect(() => {
    setLoading(true);
    fetch(url)
      .then(res => res.json())
      .then(data => {
        setData(data);
        setLoading(false);
      });
  }, [url]);
  
  return { data, loading };
}

// Components (clean!)
function ComponentA() {
  const { data, loading } = useFetch('/api/data');
  // ... render logic
}

function ComponentB() {
  const { data, loading } = useFetch('/api/data');
  // ... render logic
}
```

### Best Practices

#### 1. Naming Convention

**MUST start with "use":**

```javascript
// ✅ BENAR
function useChat() { /* ... */ }
function useWindowSize() { /* ... */ }
function useLocalStorage() { /* ... */ }

// ❌ SALAH (React tidak recognize as hook)
function chatHook() { /* ... */ }
function getWindowSize() { /* ... */ }
```

**Kenapa?**

* React ESLint rules check "use" prefix
* Convention yang jelas
* Auto-completion di editor

#### 2. Return Values

```javascript
// ✅ GOOD: Return object (named properties)
function useUser() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(false);
  
  return { user, loading, setUser }; // Named properties
}

// Usage: destructure dengan nama yang jelas
const { user, loading } = useUser();

// ✅ ALSO GOOD: Return array (positional)
function useToggle(initial = false) {
  const [value, setValue] = useState(initial);
  const toggle = () => setValue(v => !v);
  
  return [value, toggle]; // Like useState
}

// Usage: rename sesuka hati
const [isOpen, toggleOpen] = useToggle();
```

**When to use object vs array?**

* Object: Multiple return values (>2), named properties clearer
* Array: 1-2 return values, want flexible naming (like useState)

#### 3. Accept Parameters

```javascript
function useFetch(url, options = {}) {
  // ... implementation
  return { data, loading, error };
}

// Usage with different params
const users = useFetch('/api/users');
const posts = useFetch('/api/posts', { method: 'POST' });
```

#### 4. Custom Hook Can Use Other Hooks

```javascript
function useChat(initialMessages = []) {
  // Use useState
  const [messages, setMessages] = useState(initialMessages);
  const [status, setStatus] = useState('idle');
  
  // Use useRef
  const bottomRef = useRef(null);
  
  // Use useEffect
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages.length]);
  
  // Use useCallback (another hook!)
  const sendMessage = useCallback((text) => {
    // ... implementation
  }, []);
  
  return {
    messages,
    status,
    sendMessage,
    bottomRef
  };
}
```

### Common Custom Hook Patterns

#### 1. Data Fetching

```javascript
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    
    setLoading(true);
    fetch(url, { signal: controller.signal })
      .then(res => res.json())
      .then(data => {
        setData(data);
        setLoading(false);
      })
      .catch(err => {
        if (err.name !== 'AbortError') {
          setError(err);
          setLoading(false);
        }
      });

    return () => controller.abort();
  }, [url]);

  return { data, loading, error };
}
```

#### 2. Local Storage Sync

```javascript
function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const saved = localStorage.getItem(key);
    return saved !== null ? JSON.parse(saved) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

// Usage
const [theme, setTheme] = useLocalStorage('theme', 'dark');
```

#### 3. Window Size

```javascript
function useWindowSize() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return size;
}

// Usage
const { width, height } = useWindowSize();
```

#### 4. Toggle

```javascript
function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  
  const toggle = useCallback(() => {
    setValue(v => !v);
  }, []);
  
  const setTrue = useCallback(() => setValue(true), []);
  const setFalse = useCallback(() => setValue(false), []);

  return [value, { toggle, setTrue, setFalse, setValue }];
}

// Usage
const [isOpen, { toggle, setTrue, setFalse }] = useToggle();
```

***

## State vs Props vs Ref

{% hint style="info" %}
**Key Differences**

Understand when to use state, props, or ref.
{% endhint %}

### Comparison Table

| Aspek                 | State                           | Props                   | Ref                       |
| --------------------- | ------------------------------- | ----------------------- | ------------------------- |
| **Source**            | Component sendiri               | Parent component        | Component sendiri         |
| **Ownership**         | Private                         | Shared from parent      | Private                   |
| **Mutability**        | Immutable (update via setState) | Read-only               | Mutable (ref.current = x) |
| **Re-render trigger** | ✅ Yes                           | ✅ Yes (if props change) | ❌ No                      |
| **Use case**          | UI data yang berubah            | Pass data down tree     | Non-UI persistent values  |
| **Example**           | Form input, toggle, list        | User data, config       | DOM refs, timer IDs       |

### When to Use Each

#### Use State When:

```javascript
// Data yang mempengaruhi UI dan bisa berubah
const [isOpen, setIsOpen] = useState(false);
const [count, setCount] = useState(0);
const [items, setItems] = useState([]);
```

**Criteria:**

* Data yang ditampilkan di UI
* Perubahan data perlu memicu re-render
* User interaction yang update UI

#### Use Props When:

```javascript
// Pass data dari parent ke child
function Parent() {
  const [user, setUser] = useState({ name: 'John' });
  
  return <Child user={user} onUpdate={setUser} />;
}

function Child({ user, onUpdate }) {
  // Receive data dan callbacks dari parent
  return <div>{user.name}</div>;
}
```

**Criteria:**

* Data dari parent component
* Configuration/settings
* Event handlers dari parent

#### Use Ref When:

```javascript
// Data yang tidak perlu memicu re-render
const inputRef = useRef(null);           // DOM reference
const timerRef = useRef(null);           // Timer ID
const prevValueRef = useRef();           // Previous value
const instanceRef = useRef(null);        // External instance
```

**Criteria:**

* DOM manipulation
* Storing non-UI values (timer IDs, subscriptions, instances)
* Storing previous values untuk comparison
* Any mutable value yang tidak perlu trigger render

***

## Common Patterns

{% hint style="info" %}
**Best Practices**

Learn common patterns used in production React applications.
{% endhint %}

### 1. Conditional State Updates

```javascript
// Update state hanya jika kondisi terpenuhi
const handleSubmit = (data) => {
  if (data.isValid) {
    setFormData(data);
  }
};
```

### 2. Debounced State Updates

```javascript
function SearchInput() {
  const [query, setQuery] = useState('');
  const [debouncedQuery, setDebouncedQuery] = useState('');

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedQuery(query);
    }, 500);

    return () => clearTimeout(timer);
  }, [query]);

  // Use debouncedQuery for API calls
  useEffect(() => {
    if (debouncedQuery) {
      fetch(`/api/search?q=${debouncedQuery}`);
    }
  }, [debouncedQuery]);

  return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
```

### 3. Derived State

```javascript
// ❌ Don't store derived values in state
function TodoList() {
  const [todos, setTodos] = useState([]);
  const [activeTodos, setActiveTodos] = useState([]); // ❌ Redundant!
  
  // Need to sync both states - error-prone
}

// ✅ Calculate derived values directly
function TodoList() {
  const [todos, setTodos] = useState([]);
  const activeTodos = todos.filter(t => !t.completed); // ✅ Derived
  
  // Always in sync!
}
```

### 4. State Machine Pattern

```javascript
function AsyncButton() {
  const [status, setStatus] = useState('idle');
  // 'idle' | 'loading' | 'success' | 'error'

  const handleClick = async () => {
    setStatus('loading');
    
    try {
      await fetch('/api/action');
      setStatus('success');
      setTimeout(() => setStatus('idle'), 2000);
    } catch (error) {
      setStatus('error');
    }
  };

  return (
    <button onClick={handleClick} disabled={status === 'loading'}>
      {status === 'loading' && 'Loading...'}
      {status === 'success' && '✓ Success'}
      {status === 'error' && '✗ Error'}
      {status === 'idle' && 'Click me'}
    </button>
  );
}
```

### 5. Optimistic Updates

```javascript
function TodoList() {
  const [todos, setTodos] = useState([]);

  const addTodo = async (text) => {
    const tempId = Date.now();
    const newTodo = { id: tempId, text, completed: false };
    
    // Optimistic update (immediate UI update)
    setTodos(prev => [...prev, newTodo]);
    
    try {
      const response = await fetch('/api/todos', {
        method: 'POST',
        body: JSON.stringify({ text })
      });
      const savedTodo = await response.json();
      
      // Replace temp todo with real one
      setTodos(prev => prev.map(t => t.id === tempId ? savedTodo : t));
    } catch (error) {
      // Rollback on error
      setTodos(prev => prev.filter(t => t.id !== tempId));
      alert('Failed to add todo');
    }
  };

  return (/* ... */);
}
```

***

## Anti-Patterns to Avoid

{% hint style="danger" %}
**Common Mistakes**

Avoid these anti-patterns that lead to bugs and performance issues.
{% endhint %}

### 1. ❌ Calling setState in Render

```javascript
// ❌ INFINITE LOOP
function Component() {
  const [count, setCount] = useState(0);
  
  setCount(count + 1); // Called every render → trigger render → call again → ...
  
  return <div>{count}</div>;
}

// ✅ FIX: Move to event handler or useEffect
function Component() {
  const [count, setCount] = useState(0);
  
  useEffect(() => {
    setCount(1); // Only once on mount
  }, []);
  
  return <div>{count}</div>;
}
```

### 2. ❌ Direct State Mutation

```javascript
// ❌ WRONG
const [items, setItems] = useState([1, 2, 3]);
items.push(4);        // Mutating state directly!
setItems(items);      // React won't detect change

// ✅ CORRECT
setItems([...items, 4]); // New array reference
```

### 3. ❌ Not Using Functional Updates

```javascript
// ❌ WRONG (stale closure)
function Counter() {
  const [count, setCount] = useState(0);
  
  const increment = () => {
    setTimeout(() => {
      setCount(count + 1); // count might be stale after 1 second
    }, 1000);
  };
}

// ✅ CORRECT
function Counter() {
  const [count, setCount] = useState(0);
  
  const increment = () => {
    setTimeout(() => {
      setCount(prev => prev + 1); // Always get latest value
    }, 1000);
  };
}
```

### 4. ❌ Over-using State

```javascript
// ❌ TOO MUCH STATE
function UserProfile({ user }) {
  const [firstName, setFirstName] = useState(user.firstName);
  const [lastName, setLastName] = useState(user.lastName);
  const [fullName, setFullName] = useState(`${user.firstName} ${user.lastName}`); // ❌ Derived!
  
  // Need to sync fullName manually - error-prone
}

// ✅ SIMPLER
function UserProfile({ user }) {
  const [firstName, setFirstName] = useState(user.firstName);
  const [lastName, setLastName] = useState(user.lastName);
  const fullName = `${firstName} ${lastName}`; // ✅ Computed on-the-fly
}
```

### 5. ❌ Missing Effect Dependencies

```javascript
// ❌ WRONG
function Component({ userId }) {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    fetch(`/api/users/${userId}`) // Uses userId
      .then(res => res.json())
      .then(data => setUser(data));
  }, []); // ❌ Missing userId in deps!
  
  // Won't re-fetch when userId changes!
}

// ✅ CORRECT
useEffect(() => {
  fetch(`/api/users/${userId}`)
    .then(res => res.json())
    .then(data => setUser(data));
}, [userId]); // ✅ Include userId
```

### 6. ❌ Using Ref for UI State

```javascript
// ❌ WRONG
function Counter() {
  const countRef = useRef(0);
  
  const increment = () => {
    countRef.current++; // Updates ref but doesn't re-render!
  };
  
  return <div>{countRef.current}</div>; // UI won't update!
}

// ✅ CORRECT
function Counter() {
  const [count, setCount] = useState(0);
  
  const increment = () => {
    setCount(prev => prev + 1); // Triggers re-render
  };
  
  return <div>{count}</div>; // UI updates!
}
```

***

## Mental Models

{% hint style="success" %}
**Conceptual Understanding**

Develop mental models to think like React.
{% endhint %}

### 1. State = Snapshot

Setiap render memiliki "snapshot" of state.

```javascript
function Counter() {
  const [count, setCount] = useState(0);
  
  const handleClick = () => {
    setCount(count + 1);
    console.log(count); // Still 0! (snapshot from current render)
    
    setTimeout(() => {
      console.log(count); // Still 0! (captured in closure)
    }, 1000);
  };
  
  // Next render will have count = 1
}
```

**Think:** State tidak "berubah" di dalam render, tapi next render dapat nilai baru.

### 2. Effect = Sync with External System

useEffect is for **synchronizing** component dengan external systems.

```javascript
// Sync document title dengan count
useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]);

// Sync subscription dengan userId
useEffect(() => {
  const sub = api.subscribe(userId, handleData);
  return () => sub.unsubscribe();
}, [userId]);
```

**Think:** "Keep X in sync with Y"

### 3. Ref = Sticky Note

Ref seperti sticky note yang bisa kamu tulis kapan saja, tidak mempengaruhi render.

```javascript
const noteRef = useRef('initial note');

// Write on note (no re-render)
noteRef.current = 'updated note';

// Read note
console.log(noteRef.current);
```

**Think:** Ref untuk "note to self" yang tidak perlu ditampilkan di UI.

### 4. Custom Hook = Recipe

Custom hook seperti resep masakan yang bisa dipakai berulang.

```javascript
// Recipe for fetching data
function useFetch(url) {
  // Ingredients (hooks)
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  
  // Instructions (logic)
  useEffect(() => {
    fetch(url).then(/* ... */);
  }, [url]);
  
  // Result
  return { data, loading };
}

// Use recipe in different places
const userRecipe = useFetch('/api/users');
const postRecipe = useFetch('/api/posts');
```

**Think:** Extract repeated "recipes" (logic) into custom hooks.

***

## Summary

### Kapan Pakai Hooks?

```
UI data yang berubah → useState
Side effect setelah render → useEffect
Non-UI mutable value → useRef
Reusable logic → Custom Hook
```

### Decision Tree

```
Perlu data yang persist? 
├─ Yes: Trigger re-render?
│  ├─ Yes → useState
│  └─ No → useRef
└─ No: Use regular variable

Perlu operasi setelah render?
└─ Yes → useEffect

Logic repeated di multiple components?
└─ Yes → Custom Hook
```

### Key Takeaways

1. **State immutable** → Always create new reference
2. **Functional updates** → When new state depends on old state
3. **Effect dependencies** → Include all values used inside effect
4. **Ref not for UI** → Ref updates don't trigger renders
5. **Custom hooks reusable** → Extract and share logic
6. **Follow Rules of Hooks** → Top-level, React functions only

***

## Modern React Ecosystem & Hooks

{% hint style="success" %}
**Advanced Topics - Production Ready**

Explore modern libraries and patterns used in professional React development.
{% endhint %}

{% hint style="info" %}
**What You'll Learn:**

* State Management beyond useState (Context API, Zustand, Redux Toolkit)
* Data Fetching patterns (Fetch API, Axios, TanStack Query)
* Form Validation with schemas (Zod, React Hook Form)
* Next.js integration with hooks (App Router, Server Components)
* How to choose the right library for your project
  {% endhint %}

Bagian ini menjelaskan bagaimana hooks bekerja dengan library dan framework modern di ekosistem React.

***

## State Management Libraries

{% hint style="info" %}
**Choosing State Management**

Learn when to use Context API, Zustand, or Redux Toolkit.
{% endhint %}

### Context API (Built-in React)

**Apa itu Context API?**

Context API adalah cara built-in React untuk share data across component tree tanpa props drilling.

**Kapan Pakai Context?**

* ✅ Theme (dark/light mode)
* ✅ Authentication state
* ✅ Language/i18n
* ✅ User preferences
* ⚠️ Not for frequently changing data (performance issues)

**Implementation dengan Hooks:**

```javascript
// 1. Create Context
import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext(null);

// 2. Provider Component
export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  
  const toggleTheme = () => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light');
  };
  
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// 3. Custom Hook untuk consume Context
export function useTheme() {
  const context = useContext(ThemeContext);
  
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  
  return context;
}

// 4. Usage di Component
function App() {
  return (
    <ThemeProvider>
      <Header />
      <Content />
    </ThemeProvider>
  );
}

function Header() {
  const { theme, toggleTheme } = useTheme();
  
  return (
    <header className={theme}>
      <button onClick={toggleTheme}>
        Switch to {theme === 'light' ? 'dark' : 'light'}
      </button>
    </header>
  );
}
```

**Context Best Practices:**

```javascript
// ✅ GOOD: Separate contexts for different concerns
const AuthContext = createContext();
const ThemeContext = createContext();
const LanguageContext = createContext();

// ❌ BAD: One massive context
const AppContext = createContext(); // { auth, theme, language, ... }

// ✅ GOOD: Split value untuk optimization
function UserProvider({ children }) {
  const [user, setUser] = useState(null);
  
  // Memoize untuk prevent unnecessary re-renders
  const value = useMemo(() => ({ user, setUser }), [user]);
  
  return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
}

// ✅ GOOD: Error handling di custom hook
export function useUser() {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error('useUser must be used within UserProvider');
  }
  return context;
}
```

**Limitations Context API:**

* ⚠️ Any value change = all consumers re-render (no selector)
* ⚠️ Not built for high-frequency updates
* ⚠️ Can cause performance issues in large apps

***

### Zustand (Lightweight State Management)

**Apa itu Zustand?**

Zustand adalah state management library yang simple, fast, dan scalable dengan API minimal.

**Kenapa Zustand?**

* ✅ Minimal boilerplate (no providers, actions, reducers)
* ✅ Better performance than Context
* ✅ Built-in selectors (prevent unnecessary re-renders)
* ✅ Works outside React (vanilla JS)
* ✅ DevTools support
* ✅ TypeScript friendly

**Installation:**

```bash
npm install zustand
```

**Basic Usage:**

```javascript
import { create } from 'zustand';

// 1. Create Store
const useStore = create((set) => ({
  // State
  count: 0,
  user: null,
  
  // Actions
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
  setUser: (user) => set({ user }),
  reset: () => set({ count: 0, user: null })
}));

// 2. Use in Components
function Counter() {
  // Subscribe to specific state (selector)
  const count = useStore((state) => state.count);
  const increment = useStore((state) => state.increment);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>+1</button>
    </div>
  );
}

function UserProfile() {
  // Only re-renders when user changes
  const user = useStore((state) => state.user);
  
  return <div>{user?.name}</div>;
}
```

**Advanced Zustand Patterns:**

```javascript
// 1. Async Actions
const useStore = create((set, get) => ({
  messages: [],
  isLoading: false,
  error: null,
  
  fetchMessages: async () => {
    set({ isLoading: true, error: null });
    
    try {
      const response = await fetch('/api/messages');
      const data = await response.json();
      set({ messages: data, isLoading: false });
    } catch (error) {
      set({ error: error.message, isLoading: false });
    }
  },
  
  addMessage: (message) => set((state) => ({
    messages: [...state.messages, message]
  }))
}));

// 2. Computed Values dengan Selectors
const useStore = create((set, get) => ({
  messages: [],
  
  // Computed
  get messageCount() {
    return get().messages.length;
  },
  
  get unreadCount() {
    return get().messages.filter(m => !m.read).length;
  }
}));

// Usage
function Stats() {
  const messageCount = useStore((state) => state.messageCount);
  const unreadCount = useStore((state) => state.unreadCount);
  
  return <div>{messageCount} total, {unreadCount} unread</div>;
}

// 3. Middleware (Persistence)
import { persist } from 'zustand/middleware';

const useStore = create(
  persist(
    (set) => ({
      theme: 'light',
      setTheme: (theme) => set({ theme })
    }),
    {
      name: 'app-storage', // localStorage key
    }
  )
);

// 4. Immer for Complex Updates
import { immer } from 'zustand/middleware/immer';

const useStore = create(
  immer((set) => ({
    user: { name: '', settings: { theme: 'light' } },
    
    // With Immer, you can "mutate" (draft state)
    updateTheme: (theme) => set((state) => {
      state.user.settings.theme = theme; // Looks like mutation, but immutable!
    })
  }))
);
```

**Zustand vs Context:**

| Feature        | Context API                    | Zustand                    |
| -------------- | ------------------------------ | -------------------------- |
| Boilerplate    | High (Provider, Consumer)      | Low (just create)          |
| Performance    | Poor (all consumers re-render) | Excellent (selector-based) |
| DevTools       | No                             | Yes                        |
| Outside React  | No                             | Yes                        |
| Learning Curve | Medium                         | Easy                       |
| Best For       | Low-frequency updates          | Any state management       |

***

### Redux Toolkit (Enterprise State Management)

**Apa itu Redux Toolkit?**

Redux Toolkit adalah official, opinionated Redux toolset yang simplify Redux development dengan best practices built-in.

**Kapan Pakai Redux?**

* ✅ Large applications dengan complex state
* ✅ State perlu di-share banyak component
* ✅ Butuh time-travel debugging
* ✅ Butuh middleware (logging, analytics, etc)
* ✅ Team sudah familiar dengan Redux patterns

**Installation:**

```bash
npm install @reduxjs/toolkit react-redux
```

**Redux Toolkit dengan Hooks:**

```javascript
// 1. Create Slice (state + reducers)
import { createSlice } from '@reduxjs/toolkit';

const chatSlice = createSlice({
  name: 'chat',
  initialState: {
    messages: [],
    status: 'idle',
    error: null
  },
  reducers: {
    addMessage: (state, action) => {
      // Immer inside: bisa "mutate" state
      state.messages.push(action.payload);
    },
    setStatus: (state, action) => {
      state.status = action.payload;
    },
    clearMessages: (state) => {
      state.messages = [];
    }
  }
});

export const { addMessage, setStatus, clearMessages } = chatSlice.actions;
export default chatSlice.reducer;

// 2. Create Store
import { configureStore } from '@reduxjs/toolkit';

export const store = configureStore({
  reducer: {
    chat: chatSlice.reducer,
    user: userSlice.reducer,
    // ... other slices
  }
});

// 3. Provide Store
import { Provider } from 'react-redux';

function App() {
  return (
    <Provider store={store}>
      <ChatApp />
    </Provider>
  );
}

// 4. Use in Components dengan Hooks
import { useSelector, useDispatch } from 'react-redux';

function Chat() {
  // useSelector: subscribe to state
  const messages = useSelector((state) => state.chat.messages);
  const status = useSelector((state) => state.chat.status);
  
  // useDispatch: dispatch actions
  const dispatch = useDispatch();
  
  const handleSend = (text) => {
    dispatch(addMessage({
      id: Date.now(),
      content: text,
      role: 'user'
    }));
  };
  
  return (
    <div>
      {messages.map(msg => <Message key={msg.id} {...msg} />)}
      <input onSubmit={handleSend} />
    </div>
  );
}
```

**Async Logic dengan createAsyncThunk:**

```javascript
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

// 1. Create Async Thunk
export const fetchMessages = createAsyncThunk(
  'chat/fetchMessages',
  async (userId, { rejectWithValue }) => {
    try {
      const response = await fetch(`/api/messages?user=${userId}`);
      if (!response.ok) throw new Error('Failed to fetch');
      return await response.json();
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

// 2. Handle Async States in Slice
const chatSlice = createSlice({
  name: 'chat',
  initialState: {
    messages: [],
    status: 'idle', // 'idle' | 'loading' | 'succeeded' | 'failed'
    error: null
  },
  reducers: {
    // ... sync reducers
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchMessages.pending, (state) => {
        state.status = 'loading';
        state.error = null;
      })
      .addCase(fetchMessages.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.messages = action.payload;
      })
      .addCase(fetchMessages.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload;
      });
  }
});

// 3. Use in Component
function Chat() {
  const dispatch = useDispatch();
  const { messages, status, error } = useSelector((state) => state.chat);
  
  useEffect(() => {
    dispatch(fetchMessages('user-123'));
  }, [dispatch]);
  
  if (status === 'loading') return <Spinner />;
  if (status === 'failed') return <Error message={error} />;
  
  return <MessageList messages={messages} />;
}
```

**Redux Toolkit Query (RTK Query) untuk Data Fetching:**

```javascript
// 1. Create API Slice
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (builder) => ({
    getMessages: builder.query({
      query: () => 'messages',
    }),
    sendMessage: builder.mutation({
      query: (message) => ({
        url: 'messages',
        method: 'POST',
        body: message,
      }),
    }),
  }),
});

export const { useGetMessagesQuery, useSendMessageMutation } = api;

// 2. Use in Component
function Chat() {
  // Auto-fetching, caching, refetching
  const { data: messages, isLoading, error } = useGetMessagesQuery();
  const [sendMessage, { isLoading: isSending }] = useSendMessageMutation();
  
  if (isLoading) return <Spinner />;
  
  return (
    <div>
      {messages?.map(msg => <Message key={msg.id} {...msg} />)}
      <button 
        onClick={() => sendMessage({ content: 'Hello' })}
        disabled={isSending}
      >
        Send
      </button>
    </div>
  );
}
```

**Redux Best Practices:**

```javascript
// ✅ GOOD: Normalize state shape
{
  messages: {
    byId: {
      'm1': { id: 'm1', content: '...' },
      'm2': { id: 'm2', content: '...' }
    },
    allIds: ['m1', 'm2']
  }
}

// ❌ BAD: Nested arrays
{
  messages: [
    { id: 'm1', content: '...', replies: [ /* ... */ ] }
  ]
}

// ✅ GOOD: Memoized selectors
import { createSelector } from '@reduxjs/toolkit';

const selectMessages = (state) => state.chat.messages;
const selectFilter = (state) => state.chat.filter;

export const selectFilteredMessages = createSelector(
  [selectMessages, selectFilter],
  (messages, filter) => {
    return messages.filter(msg => msg.type === filter);
  }
);
```

***

## Data Fetching Libraries

{% hint style="info" %}
**Modern Data Fetching**

Compare Fetch API, Axios, and TanStack Query for your use case.
{% endhint %}

### Native Fetch API

**Basic Fetch dengan Hooks:**

```javascript
function useMessages() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch('/api/messages');
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const json = await response.json();
        setData(json);
      } catch (e) {
        setError(e.message);
      } finally {
        setLoading(false);
      }
    }
    
    fetchData();
  }, []);
  
  return { data, loading, error };
}

// Usage
function Chat() {
  const { data: messages, loading, error } = useMessages();
  
  if (loading) return <Spinner />;
  if (error) return <Error message={error} />;
  
  return <MessageList messages={messages} />;
}
```

**Fetch dengan Abort Controller:**

```javascript
function useMessages(userId) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    const controller = new AbortController();
    
    async function fetchData() {
      try {
        const response = await fetch(`/api/messages?user=${userId}`, {
          signal: controller.signal
        });
        const json = await response.json();
        setData(json);
      } catch (e) {
        if (e.name !== 'AbortError') {
          console.error('Fetch error:', e);
        }
      } finally {
        setLoading(false);
      }
    }
    
    fetchData();
    
    // Cleanup: abort request jika component unmount
    return () => controller.abort();
  }, [userId]);
  
  return { data, loading };
}
```

***

### Axios (HTTP Client)

**Apa itu Axios?**

Axios adalah HTTP client yang lebih powerful dari fetch dengan features:

* ✅ Automatic JSON transformation
* ✅ Request/Response interceptors
* ✅ Better error handling
* ✅ Progress tracking
* ✅ Built-in timeout
* ✅ Request cancellation

**Installation:**

```bash
npm install axios
```

**Axios dengan Hooks:**

```javascript
import axios from 'axios';

// 1. Basic Usage
function useMessages() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    axios.get('/api/messages')
      .then(response => {
        setData(response.data); // auto-parsed JSON
        setLoading(false);
      })
      .catch(error => {
        setError(error.message);
        setLoading(false);
      });
  }, []);
  
  return { data, loading, error };
}

// 2. With Async/Await
function useMessages() {
  const [state, setState] = useState({
    data: null,
    loading: true,
    error: null
  });
  
  useEffect(() => {
    async function fetchData() {
      try {
        const response = await axios.get('/api/messages');
        setState({ data: response.data, loading: false, error: null });
      } catch (error) {
        setState({ data: null, loading: false, error: error.message });
      }
    }
    
    fetchData();
  }, []);
  
  return state;
}

// 3. Axios Instance dengan Config
const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  }
});

// Interceptors untuk auth
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Usage dengan instance
function useSecureMessages() {
  const [data, setData] = useState(null);
  
  useEffect(() => {
    api.get('/messages')
      .then(res => setData(res.data))
      .catch(err => console.error(err));
  }, []);
  
  return data;
}
```

**Custom Axios Hook:**

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

function useAxios(url, options = {}) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    let cancelled = false;
    const source = axios.CancelToken.source();
    
    async function fetchData() {
      try {
        const response = await axios({
          url,
          cancelToken: source.token,
          ...options
        });
        
        if (!cancelled) {
          setData(response.data);
          setLoading(false);
        }
      } catch (err) {
        if (!axios.isCancel(err) && !cancelled) {
          setError(err.message);
          setLoading(false);
        }
      }
    }
    
    fetchData();
    
    return () => {
      cancelled = true;
      source.cancel('Component unmounted');
    };
  }, [url, JSON.stringify(options)]);
  
  return { data, loading, error };
}

// Usage
function Chat() {
  const { data, loading, error } = useAxios('/api/messages', {
    method: 'GET',
    params: { limit: 50 }
  });
  
  if (loading) return <Spinner />;
  if (error) return <Error message={error} />;
  
  return <MessageList messages={data} />;
}
```

***

### TanStack Query (React Query)

**Apa itu TanStack Query?**

TanStack Query (formerly React Query) adalah powerful data fetching library dengan features:

* ✅ Automatic caching
* ✅ Background refetching
* ✅ Optimistic updates
* ✅ Pagination & infinite scroll
* ✅ Request deduplication
* ✅ Retry logic
* ✅ DevTools

**Installation:**

```bash
npm install @tanstack/react-query
```

**Setup:**

```javascript
// 1. Create Query Client
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      cacheTime: 10 * 60 * 1000, // 10 minutes
      refetchOnWindowFocus: false,
    },
  },
});

// 2. Wrap App
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <ChatApp />
    </QueryClientProvider>
  );
}
```

**Query Hooks:**

```javascript
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';

// 1. Fetch Data
function Chat() {
  const { 
    data: messages, 
    isLoading, 
    error,
    refetch 
  } = useQuery({
    queryKey: ['messages'],
    queryFn: async () => {
      const { data } = await axios.get('/api/messages');
      return data;
    },
    staleTime: 5 * 60 * 1000, // Data fresh for 5 min
  });
  
  if (isLoading) return <Spinner />;
  if (error) return <Error message={error.message} />;
  
  return (
    <div>
      <MessageList messages={messages} />
      <button onClick={refetch}>Refresh</button>
    </div>
  );
}

// 2. Mutations (POST, PUT, DELETE)
function ChatInput() {
  const queryClient = useQueryClient();
  
  const mutation = useMutation({
    mutationFn: async (message) => {
      const { data } = await axios.post('/api/messages', message);
      return data;
    },
    onSuccess: () => {
      // Invalidate cache, refetch
      queryClient.invalidateQueries({ queryKey: ['messages'] });
    },
    onError: (error) => {
      console.error('Send failed:', error);
    }
  });
  
  const handleSend = (text) => {
    mutation.mutate({ content: text, role: 'user' });
  };
  
  return (
    <div>
      <input />
      <button 
        onClick={() => handleSend('Hello')}
        disabled={mutation.isPending}
      >
        {mutation.isPending ? 'Sending...' : 'Send'}
      </button>
      {mutation.isError && <Error message={mutation.error.message} />}
    </div>
  );
}

// 3. Optimistic Updates
function ChatWithOptimistic() {
  const queryClient = useQueryClient();
  
  const mutation = useMutation({
    mutationFn: (newMessage) => axios.post('/api/messages', newMessage),
    
    // Before mutation
    onMutate: async (newMessage) => {
      // Cancel outgoing refetches
      await queryClient.cancelQueries({ queryKey: ['messages'] });
      
      // Snapshot previous value
      const previousMessages = queryClient.getQueryData(['messages']);
      
      // Optimistically update
      queryClient.setQueryData(['messages'], (old) => 
        [...old, { ...newMessage, id: 'temp', pending: true }]
      );
      
      // Return context for rollback
      return { previousMessages };
    },
    
    // On error, rollback
    onError: (err, newMessage, context) => {
      queryClient.setQueryData(['messages'], context.previousMessages);
    },
    
    // After success/error, refetch
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['messages'] });
    },
  });
  
  return <ChatInput onSend={mutation.mutate} />;
}

// 4. Dependent Queries
function UserChat({ userId }) {
  // First query: user info
  const { data: user } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => axios.get(`/api/users/${userId}`).then(r => r.data),
  });
  
  // Second query: depends on first
  const { data: messages } = useQuery({
    queryKey: ['messages', user?.id],
    queryFn: () => axios.get(`/api/messages?user=${user.id}`).then(r => r.data),
    enabled: !!user, // Only run if user exists
  });
  
  return <MessageList messages={messages} />;
}

// 5. Infinite Query (Pagination)
function InfiniteMessages() {
  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useInfiniteQuery({
    queryKey: ['messages', 'infinite'],
    queryFn: async ({ pageParam = 0 }) => {
      const { data } = await axios.get(`/api/messages?cursor=${pageParam}`);
      return data;
    },
    getNextPageParam: (lastPage) => lastPage.nextCursor,
  });
  
  return (
    <div>
      {data?.pages.map((page, i) => (
        <React.Fragment key={i}>
          {page.messages.map(msg => <Message key={msg.id} {...msg} />)}
        </React.Fragment>
      ))}
      
      {hasNextPage && (
        <button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
          {isFetchingNextPage ? 'Loading...' : 'Load More'}
        </button>
      )}
    </div>
  );
}
```

**TanStack Query Best Practices:**

```javascript
// ✅ GOOD: Use query keys effectively
const messagesQuery = useQuery({
  queryKey: ['messages', { userId, filter }], // Includes dependencies
  queryFn: () => fetchMessages(userId, filter),
});

// ✅ GOOD: Custom hooks for reusability
function useMessages(userId, options = {}) {
  return useQuery({
    queryKey: ['messages', userId],
    queryFn: () => axios.get(`/api/messages?user=${userId}`).then(r => r.data),
    ...options,
  });
}

// Usage
const { data: messages } = useMessages('user-123', {
  refetchInterval: 30000, // Poll every 30s
});

// ✅ GOOD: Prefetching
function MessageList() {
  const queryClient = useQueryClient();
  
  const handleHover = (userId) => {
    queryClient.prefetchQuery({
      queryKey: ['user', userId],
      queryFn: () => fetchUser(userId),
    });
  };
  
  return messages.map(msg => (
    <Message onHover={() => handleHover(msg.userId)} />
  ));
}
```

***

## Form Validation Libraries

{% hint style="info" %}
**Type-Safe Forms**

Build robust forms with Zod schema validation and React Hook Form.
{% endhint %}

### Zod (Schema Validation)

**Apa itu Zod?**

Zod adalah TypeScript-first schema validation library dengan type inference.

**Installation:**

```bash
npm install zod
```

**Basic Usage:**

```javascript
import { z } from 'zod';

// 1. Define Schema
const messageSchema = z.object({
  content: z.string()
    .min(1, 'Message cannot be empty')
    .max(1000, 'Message too long'),
  userId: z.string().uuid(),
  metadata: z.object({
    timestamp: z.date(),
    platform: z.enum(['web', 'mobile'])
  }).optional()
});

// 2. Validate Data
function sendMessage(data) {
  try {
    const validated = messageSchema.parse(data);
    // validated is type-safe!
    console.log(validated.content);
  } catch (error) {
    if (error instanceof z.ZodError) {
      console.error(error.errors);
      // [{ path: ['content'], message: 'Message cannot be empty' }]
    }
  }
}

// 3. Safe Parse (no throw)
const result = messageSchema.safeParse(data);

if (result.success) {
  console.log(result.data);
} else {
  console.error(result.error.errors);
}

// 4. Type Inference
type Message = z.infer<typeof messageSchema>;
// { content: string; userId: string; metadata?: { ... } }
```

**Zod with React Hooks:**

```javascript
import { useState } from 'react';
import { z } from 'zod';

const messageSchema = z.object({
  content: z.string().min(1).max(500),
  email: z.string().email().optional()
});

function ChatInput() {
  const [formData, setFormData] = useState({ content: '', email: '' });
  const [errors, setErrors] = useState({});
  
  const handleSubmit = (e) => {
    e.preventDefault();
    
    const result = messageSchema.safeParse(formData);
    
    if (!result.success) {
      // Extract errors
      const fieldErrors = {};
      result.error.errors.forEach(err => {
        fieldErrors[err.path[0]] = err.message;
      });
      setErrors(fieldErrors);
      return;
    }
    
    // Valid data
    sendMessage(result.data);
    setErrors({});
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input
        value={formData.content}
        onChange={(e) => setFormData({ ...formData, content: e.target.value })}
      />
      {errors.content && <span className="error">{errors.content}</span>}
      
      <button type="submit">Send</button>
    </form>
  );
}

// Advanced: Custom validation hook
function useZodForm(schema) {
  const [data, setData] = useState({});
  const [errors, setErrors] = useState({});
  
  const validate = (fieldData = data) => {
    const result = schema.safeParse(fieldData);
    
    if (!result.success) {
      const fieldErrors = {};
      result.error.errors.forEach(err => {
        fieldErrors[err.path[0]] = err.message;
      });
      setErrors(fieldErrors);
      return false;
    }
    
    setErrors({});
    return true;
  };
  
  const handleChange = (field, value) => {
    setData(prev => ({ ...prev, [field]: value }));
  };
  
  return { data, errors, handleChange, validate };
}

// Usage
function MessageForm() {
  const form = useZodForm(messageSchema);
  
  const handleSubmit = (e) => {
    e.preventDefault();
    if (form.validate()) {
      sendMessage(form.data);
    }
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input
        onChange={(e) => form.handleChange('content', e.target.value)}
      />
      {form.errors.content && <Error>{form.errors.content}</Error>}
    </form>
  );
}
```

***

### React Hook Form (Form Management)

**Apa itu React Hook Form?**

React Hook Form adalah performant form library dengan minimal re-renders.

**Installation:**

```bash
npm install react-hook-form
```

**Basic Usage:**

```javascript
import { useForm } from 'react-hook-form';

function ChatForm() {
  const {
    register,
    handleSubmit,
    formState: { errors },
    reset
  } = useForm();
  
  const onSubmit = (data) => {
    console.log(data); // { content: '...', email: '...' }
    sendMessage(data);
    reset();
  };
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register('content', {
          required: 'Message is required',
          minLength: { value: 1, message: 'Too short' },
          maxLength: { value: 500, message: 'Too long' }
        })}
      />
      {errors.content && <span>{errors.content.message}</span>}
      
      <input
        type="email"
        {...register('email', {
          pattern: { value: /^\S+@\S+$/i, message: 'Invalid email' }
        })}
      />
      {errors.email && <span>{errors.email.message}</span>}
      
      <button type="submit">Send</button>
    </form>
  );
}
```

**React Hook Form + Zod Integration:**

```javascript
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

// 1. Define Schema
const schema = z.object({
  content: z.string().min(1, 'Message required').max(500),
  email: z.string().email('Invalid email').optional(),
  priority: z.enum(['low', 'medium', 'high'])
});

// 2. Use with React Hook Form
function ChatForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset
  } = useForm({
    resolver: zodResolver(schema), // Zod validation
    defaultValues: {
      content: '',
      email: '',
      priority: 'medium'
    }
  });
  
  const onSubmit = async (data) => {
    try {
      await sendMessage(data);
      reset();
    } catch (error) {
      console.error(error);
    }
  };
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <textarea {...register('content')} />
      {errors.content && <span>{errors.content.message}</span>}
      
      <input type="email" {...register('email')} />
      {errors.email && <span>{errors.email.message}</span>}
      
      <select {...register('priority')}>
        <option value="low">Low</option>
        <option value="medium">Medium</option>
        <option value="high">High</option>
      </select>
      
      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? 'Sending...' : 'Send'}
      </button>
    </form>
  );
}
```

***

## Next.js Integration dengan Hooks

{% hint style="success" %}
**Full-Stack React**

Learn how hooks work in Next.js App Router with Server and Client Components.
{% endhint %}

### Next.js Overview

Next.js adalah React framework dengan features:

* ✅ Server-Side Rendering (SSR)
* ✅ Static Site Generation (SSG)
* ✅ API Routes
* ✅ File-based routing
* ✅ Built-in optimization
* ✅ Middleware

**Semua React Hooks tetap bekerja di Next.js!**

### Server Components vs Client Components

**Next.js 13+ dengan App Router:**

```javascript
// app/chat/page.js (Server Component by default)

// ❌ Tidak bisa pakai hooks di Server Component
export default async function ChatPage() {
  // Server-side data fetching
  const messages = await fetchMessages();
  
  return <MessageList messages={messages} />;
}

// app/chat-input.jsx (Client Component)
'use client'; // Mark as client component

import { useState } from 'react';

export default function ChatInput() {
  // ✅ Hooks works in Client Components
  const [text, setText] = useState('');
  
  return (
    <input 
      value={text} 
      onChange={(e) => setText(e.target.value)} 
    />
  );
}
```

### Data Fetching Patterns di Next.js

**1. Server Component (Recommended):**

```javascript
// app/chat/page.js
async function getMessages() {
  const res = await fetch('https://api.example.com/messages', {
    cache: 'no-store' // Always fresh
  });
  return res.json();
}

export default async function ChatPage() {
  const messages = await getMessages();
  
  return <MessageList messages={messages} />;
}
```

**2. Client Component dengan useEffect:**

```javascript
'use client';

import { useState, useEffect } from 'react';

export default function ChatClient() {
  const [messages, setMessages] = useState([]);
  
  useEffect(() => {
    fetch('/api/messages')
      .then(r => r.json())
      .then(setMessages);
  }, []);
  
  return <MessageList messages={messages} />;
}
```

**3. SWR (Recommended for Client-Side):**

```javascript
'use client';

import useSWR from 'swr';

const fetcher = (url) => fetch(url).then(r => r.json());

export default function ChatClient() {
  const { data, error, mutate } = useSWR('/api/messages', fetcher, {
    refreshInterval: 3000, // Poll every 3s
  });
  
  if (error) return <Error />;
  if (!data) return <Loading />;
  
  return <MessageList messages={data} onUpdate={mutate} />;
}
```

**4. TanStack Query di Next.js:**

```javascript
// app/providers.jsx
'use client';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

export function Providers({ children }) {
  const [queryClient] = useState(() => new QueryClient());
  
  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  );
}

// app/layout.js
import { Providers } from './providers';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

// app/chat/page.jsx
'use client';

import { useQuery } from '@tanstack/react-query';

export default function ChatPage() {
  const { data } = useQuery({
    queryKey: ['messages'],
    queryFn: () => fetch('/api/messages').then(r => r.json())
  });
  
  return <MessageList messages={data} />;
}
```

### Next.js Specific Hooks

```javascript
'use client';

// 1. useRouter - Navigation
import { useRouter } from 'next/navigation';

function BackButton() {
  const router = useRouter();
  
  return (
    <button onClick={() => router.back()}>
      Back
    </button>
  );
}

// 2. usePathname - Current path
import { usePathname } from 'next/navigation';

function Navigation() {
  const pathname = usePathname();
  
  return (
    <nav>
      <a href="/" className={pathname === '/' ? 'active' : ''}>
        Home
      </a>
    </nav>
  );
}

// 3. useSearchParams - Query params
import { useSearchParams } from 'next/navigation';

function ChatPage() {
  const searchParams = useSearchParams();
  const filter = searchParams.get('filter'); // ?filter=unread
  
  return <MessageList filter={filter} />;
}

// 4. useParams - Dynamic route params
import { useParams } from 'next/navigation';

function UserChat() {
  const params = useParams(); // { userId: '123' }
  
  return <Chat userId={params.userId} />;
}
```

***

## Library Comparison & Decision Making

{% hint style="info" %}
**Making Smart Choices**

Use decision trees and comparison tables to pick the right tools.
{% endhint %}

### State Management Decision Tree

```
Application Size?
├─ Small (< 5 components)
│  └─ Use useState + Context ✅
│
├─ Medium (5-20 components)
│  ├─ Frequent updates?
│  │  ├─ Yes → Zustand ✅
│  │  └─ No → Context ✅
│  └─ Need DevTools? → Zustand ✅
│
└─ Large (> 20 components)
   ├─ Team familiar with Redux?
   │  ├─ Yes → Redux Toolkit ✅
   │  └─ No → Zustand ✅
   └─ Complex async logic?
      └─ Yes → Redux Toolkit + RTK Query ✅
```

### Data Fetching Decision Tree

```
Where to fetch?
├─ Server (Next.js)
│  └─ Server Components ✅ (await fetch)
│
└─ Client
   ├─ Simple fetch?
   │  └─ useEffect + fetch/axios ✅
   │
   ├─ Need caching/optimistic updates?
   │  └─ TanStack Query ✅
   │
   ├─ Real-time data?
   │  ├─ Next.js → SWR ✅
   │  └─ React → TanStack Query ✅
   │
   └─ GraphQL?
      └─ Apollo Client / Relay
```

### Form Handling Decision Tree

```
Form Complexity?
├─ Simple (1-3 fields)
│  └─ useState ✅
│
├─ Medium (4-10 fields)
│  ├─ Need validation?
│  │  ├─ Yes → React Hook Form + Zod ✅
│  │  └─ No → React Hook Form ✅
│  └─ Complex validation logic?
│     └─ Zod schema validation ✅
│
└─ Complex (> 10 fields, multi-step)
   └─ React Hook Form + Zod + Form Wizard ✅
```

***

## Best Practices Summary

### State Management

```javascript
// ✅ GOOD: Use right tool for the job
// Local state
const [count, setCount] = useState(0);

// Shared across few components
const { user } = useContext(UserContext);

// Global state with high-frequency updates
const messages = useStore(state => state.messages);

// Complex state machine
const [state, dispatch] = useReducer(reducer, initialState);
```

### Data Fetching

```javascript
// ✅ GOOD: Handle loading and error states
const { data, isLoading, error } = useQuery(['messages'], fetchMessages);

if (isLoading) return <Spinner />;
if (error) return <Error message={error.message} />;

return <MessageList messages={data} />;

// ✅ GOOD: Cancel requests on unmount
useEffect(() => {
  const controller = new AbortController();
  
  fetch('/api/messages', { signal: controller.signal })
    .then(/* ... */);
  
  return () => controller.abort();
}, []);
```

### Form Validation

```javascript
// ✅ GOOD: Validate early, validate often
const schema = z.object({
  content: z.string().min(1).max(500)
});

const { register, handleSubmit, formState: { errors } } = useForm({
  resolver: zodResolver(schema),
  mode: 'onBlur' // Validate on blur
});
```

***

{% hint style="success" %}
**Happy Learning!**

Modern React ecosystem bisa overwhelming, tapi ingat: **mulai simple, scale as needed**. Tidak perlu pakai semua library dari awal. Master hooks dulu, baru tambahkan tools sesuai kebutuhan project.

Konsep hooks butuh waktu untuk "click". Jangan frustasi jika belum paham sempurna. Keep practicing dan refer back to this document saat butuh!
{% endhint %}

***

**Pagination**

* **Previous:** [INSTRUCTOR\_NOTES\_GITBOOK](broken://spaces/2CXNZNIhBqo1Vfuy2vnu/pages/9e4e831ca56db27c98012fd6beb0b9aee7d74ab4)
* **Next:** [Step 1 — useState (State Management)](broken://spaces/2CXNZNIhBqo1Vfuy2vnu/pages/7a92IjPQRNOQFZa89MZq)
