# Referensi Cepat React

*Component, hook, state, effect, pola*

> Source: React Documentation (react.dev) · MIT

## Dasar JSX

### Ekspresi & Atribut

```
const name = "Alice";
const el = <h1>Hello, {name}!</h1>;
const img = <img src={url} alt="photo" />;
```

### Aturan JSX

| Command | Description |
|---------|-------------|
| `{expression}` | Sisipkan ekspresi JS apa pun |
| `className` | Gunakan sebagai pengganti `class` |
| `htmlFor` | Gunakan sebagai pengganti `for` |
| `style={{color: 'red'}}` | Inline style sebagai objek |
| `<Component />` | Tag self-closing wajib digunakan |
| `<> ... </>` | Fragment (tanpa node DOM tambahan) |

## Component

### Function Component

```
function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}

// Arrow function variant
const Greeting = ({ name }) => (
  <h1>Hello, {name}!</h1>
);
```

### Props

```
function Card({ title, children }) {
  return (
    <div className="card">
      <h2>{title}</h2>
      {children}
    </div>
  );
}

<Card title="Welcome">
  <p>Content here</p>
</Card>
```

### Default Props

```
function Button({ label = "Click me", onClick }) {
  return <button onClick={onClick}>{label}</button>;
}
```

## State (useState)

### State Dasar

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

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}
```

### Update Fungsional

```
setCount(prev => prev + 1); // use prev state
setItems(prev => [...prev, newItem]); // arrays
setUser(prev => ({...prev, name: "Bob"})); // objects
```

### Aturan State

| Command | Description |
|---------|-------------|
| `Update immutable` | Jangan pernah mutasi state langsung |
| `Async batching` | Update bisa digabungkan (batched) |
| `Bentuk fungsional` | Gunakan `prev =>` saat bergantung pada state sebelumnya |

## Effect (useEffect)

### Pola Effect

```
import { useEffect } from "react";

// Run on every render
useEffect(() => { /* ... */ });

// Run once on mount
useEffect(() => { /* ... */ }, []);

// Run when deps change
useEffect(() => { /* ... */ }, [count]);

// Cleanup on unmount
useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);
}, []);
```

## List & Key

```
function TodoList({ items }) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.text}</li>
      ))}
    </ul>
  );
}
```

*Key harus ID yang stabil dan unik — hindari index array sebagai key*

## Penanganan Event

### Event

```
<button onClick={handleClick}>Click</button>
<button onClick={() => handleDelete(id)}>Del</button>
<input onChange={(e) => setVal(e.target.value)} />
<form onSubmit={(e) => {
  e.preventDefault();
  handleSubmit();
}}>
```

### Event Umum

| Command | Description |
|---------|-------------|
| `onClick` | Klik mouse |
| `onChange` | Perubahan nilai input |
| `onSubmit` | Submit form |
| `onKeyDown` | Tombol ditekan |
| `onFocus / onBlur` | Fokus didapat / hilang |
| `onMouseEnter` | Mouse masuk ke elemen |

## Render Kondisional

```
// Ternary
{isLoggedIn ? <Dashboard /> : <Login />}

// Logical AND (short-circuit)
{hasError && <ErrorBanner />}

// Early return
function Page({ user }) {
  if (!user) return <Login />;
  return <Dashboard user={user} />;
}
```

## Hook

### useRef

```
const inputRef = useRef(null);
// Access: inputRef.current.focus();
<input ref={inputRef} />
```

*useRef menyimpan nilai antar render tanpa memicu re-render*

### useMemo & useCallback

```
// Memoize expensive computation
const sorted = useMemo(
  () => items.sort(compareFn),
  [items]
);

// Memoize callback
const handleClick = useCallback(
  () => setCount(c => c + 1),
  []
);
```

### useContext

```
import { useContext } from "react";
const value = useContext(MyContext);
```

## Custom Hook

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

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

  return [value, setValue];
}

// Usage
const [name, setName] = useLocalStorage("name", "");
```

*Custom hook harus dimulai dengan 'use'*

## Context API

### Buat & Sediakan

```
import { createContext, useContext } from "react";

const ThemeCtx = createContext("light");

function App() {
  return (
    <ThemeCtx.Provider value="dark">
      <Page />
    </ThemeCtx.Provider>
  );
}
```

### Konsumsi

```
function Page() {
  const theme = useContext(ThemeCtx); // "dark"
  return <div className={theme}>...</div>;
}
```
