| 1 | --- |
| 2 | title: "hx-optimistic" |
| 3 | description: "Shows optimistic content during the request" |
| 4 | --- |
| 5 | |
| 6 | The `hx-optimistic` attribute enables optimistic UI updates before a response arrives. |
| 7 | |
| 8 | **Note:** This is an extension attribute. To use it, you must include the optimistic extension. |
| 9 | |
| 10 | The `hx-optimistic` attribute allows you to show optimistic content immediately while a request is in flight, providing |
| 11 | instant user feedback before the server responds. |
| 12 | |
| 13 | ## Syntax |
| 14 | |
| 15 | ```html |
| 16 | <div hx-post="/like" hx-optimistic="#liked-state">Like</div> |
| 17 | ``` |
| 18 | |
| 19 | ## Installation |
| 20 | |
| 21 | Load the extension in your htmx configuration: |
| 22 | |
| 23 | ```javascript |
| 24 | htmx.config.extensions = 'optimistic'; |
| 25 | ``` |
| 26 | |
| 27 | Or load the extension file directly (if available as a separate extension). |
| 28 | |
| 29 | ## Basic Usage |
| 30 | |
| 31 | The attribute takes a CSS selector that points to the optimistic content to swap in: |
| 32 | |
| 33 | ```html |
| 34 | <div hx-post="/like" hx-optimistic="#liked-state"> |
| 35 | <div id="unliked-state">♡ Like</div> |
| 36 | </div> |
| 37 | |
| 38 | <template id="liked-state"> |
| 39 | <div>♥ Liked!</div> |
| 40 | </template> |
| 41 | ``` |
| 42 | |
| 43 | ## How It Works |
| 44 | |
| 45 | 1. When the request is triggered, htmx immediately swaps in the optimistic content |
| 46 | 2. The original content is saved |
| 47 | 3. When the server responds, the response content replaces the optimistic content |
| 48 | 4. If the request fails, the original content is restored |
| 49 | |
| 50 | ## Notes |
| 51 | |
| 52 | * Optimistic content is swapped in immediately when the request is triggered |
| 53 | * If the request fails, the optimistic content is rolled back to the original |
| 54 | * Useful for providing immediate feedback to users |
| 55 | * Can use `<template>` tags or any hidden element as the source of optimistic content |
| 56 | |
| 57 | ## See Also |
| 58 | |
| 59 | * [Extensions](/extensions) |