# DOM Updates

- **Section:** Core Concepts
- **URL:** https://refast.fastapicloud.dev/docs/concepts/updates
- **Markdown:** https://refast.fastapicloud.dev/docs/concepts/updates.md
- **Source:** https://github.com/idling-mind/refast-docs/blob/main/docs/pages/concepts/updates.py
- **Live examples:** the widgets on this page need a browser; open the URL above to try them.
- **Applies to:** refast 0.12.2

## Overview

Refast gives you two strategies for pushing UI changes from Python:

1. **Full re-render** — re-run the page function and send the entire component tree.
2. **Targeted updates** — surgically modify one element by `id` without re-rendering anything else.

Use full re-renders for simplicity. Use targeted updates when you need to stream data,
update high-frequency values, or preserve focus and scroll position in unrelated parts
of the page.

---

## Full re-render: `ctx.refresh()`

`ctx.refresh()` re-runs the current page function with the latest state and sends the
resulting component tree to the client.

```python
async def increment(ctx: Context):
    ctx.state["count"] = ctx.state.get("count", 0) + 1
    await ctx.refresh()                         # full page re-render
```

Pass `target_id` to re-render only a subtree — Refast runs the page function, finds the
component with that id, and sends only that node as a targeted `replace` update.

```python
async def increment(ctx: Context):
    ctx.state["count"] = ctx.state.get("count", 0) + 1
    await ctx.refresh(target_id="counter-panel")  # only counter-panel is replaced
```

---

## Targeted updates

All methods below send a single WebSocket message that modifies one element.
The target component **must have an `id` prop** — Refast uses that to locate the DOM node.

### `ctx.replace(id, component)`

Swap an element entirely with a new component tree.

```python
await ctx.replace("my-card", Card(children=[Text("Updated content!")]))
```

### `ctx.append(id, component)` / `ctx.prepend(id, component)`

Add a child to the **end** or **beginning** of a container.

```python
await ctx.append("chat-list", MessageBubble(text="New message"))
await ctx.prepend("notifications", NotificationItem(msg="New alert"))
```

### `ctx.remove(id)`

Delete an element from the DOM.

```python
await ctx.remove("notification-42")
```

### `ctx.update_props(id, props)`

Change specific props without replacing the component.
Supports a special `"children"` key to replace all children at once.

```python
# Toggle a button
await ctx.update_props("submit-btn", {"disabled": True, "variant": "ghost"})

# Clear a container's children
await ctx.update_props("result-panel", {"children": []})

# Replace children with new components
await ctx.update_props("result-panel", {
    "children": [Heading("Results", level=3), Text("3 items found")],
})
```

### `ctx.update_text(id, text)`

Update only the text content of a component — the lightest possible update.

```python
await ctx.update_text("status-label", "Processing…")
await ctx.update_text("status-label", "Done!")
```

### `ctx.append_prop(id, prop_name, value)`

Append a value to a component's prop.
For string props it concatenates; for list props it appends (or extends for lists).
Primarily used for streaming text into a `Markdown` or `Text` component.

```python
# Stream LLM tokens into a Markdown component
async def stream_answer(ctx: Context):
    await ctx.update_props("ai-output", {"streaming": True})
    async for chunk in llm_stream():
        await ctx.append_prop("ai-output", "content", chunk)
    await ctx.update_props("ai-output", {"streaming": False})

# Append a data point to a chart
await ctx.append_prop("live-chart", "data", {"x": timestamp, "y": value})
```

---

## Performance comparison

| Method | Network cost | Re-render | Best for |
|---|---|---|---|
| `ctx.refresh()` | Full tree | Full | State-driven pages |
| `ctx.refresh(target_id=...)` | One subtree | Partial | Localised state changes |
| `ctx.replace()` | One component | None | Section swap |
| `ctx.append()` / `ctx.prepend()` | One component | None | Lists, feeds, chat |
| `ctx.remove()` | One ID | None | Deleting items |
| `ctx.update_props()` | Changed props only | None | Disabling, styling |
| `ctx.update_text()` | New string | None | Status labels, counters |
| `ctx.append_prop()` | Value delta | None | Streaming, live charts |

---

## Example: long-running task with progress

```python
import asyncio
from refast import Context
from refast.components import Progress, Text

async def run_task(ctx: Context):
    for i in range(10):
        await asyncio.sleep(0.5)
        pct = (i + 1) * 10
        await ctx.update_props("task-progress", {"value": pct})
        await ctx.update_text("task-status", f"Progress: {pct}%")
    await ctx.update_text("task-status", "Complete!")
```

---

## Live demo

Try the targeted update operations below. Each button calls a Python callback that
sends a focused WebSocket message — no full page re-render happens.

---

## Important notes

- **IDs must be unique** in the rendered tree. Duplicate ids cause undefined behaviour.
- Targeted updates are **additive for the session** — items you append survive until the
  WebSocket session ends (tab close / reload). Use `ctx.refresh(target_id=...)` or
  `ctx.update_props(..., {"children": [...]})` to restore a known state.
- `ctx.update_props()` with `"children"` **replaces** all children of the target; it is
  not the same as appending.
- Targeted updates bypass the page render function, so they can run inside
  `asyncio.create_task()` background jobs without blocking the event loop.

---

## Next Steps

- [Routing & Navigation](https://refast.fastapicloud.dev/docs/concepts/routing) — SPA navigation and `ctx.load()`
- [Streaming](https://refast.fastapicloud.dev/docs/concepts/streaming) — Incremental text updates with `ctx.stream()`
- [Background Jobs](https://refast.fastapicloud.dev/docs/concepts/background) — Broadcasting updates to all clients

---

Part of the Refast documentation: [all pages](https://refast.fastapicloud.dev/llms.txt), [everything on one page](https://refast.fastapicloud.dev/llms-full.txt), [search](https://refast.fastapicloud.dev/api/search?q=save_prop).
