Getting Started
Core Concepts
Control
Interactivity
Performance
Pushing Data
HTMX Extensions
Miscellaneous
Configuration
Caching Components Globally
You may want to cache components to improve performance. This is especially useful for components that are expensive to render or make external requests for data.
When a request is made for a cached component, the component is rendered and stored in memory. Subsequent requests for the same component within the cache duration will return the cached component instead of rendering it again.
To cache a component in htmgo, we offer two ways, caching globally or caching per key, this section will focus on caching globally, you will learn more about caching per key in the next section:
Methods for caching globally:
1// No arguments passed to the component
2h.Cached(duration time.Duration, cb GetElementFunc)
3// One argument passed to the component
4h.CachedT(duration time.Duration, cb GetElementFunc)
5// Two arguments passed to the component
6h.CachedT2(duration time.Duration, cb GetElementFunc)
7// Three arguments passed to the component
8h.CachedT3(duration time.Duration, cb GetElementFunc)
9// Four arguments passed to the component
10h.CachedT4(duration time.Duration, cb GetElementFunc)
For caching components per unique identifier, see Caching Components Per Key.
Usage:
1func ExpensiveComponent(ctx *h.RequestContext) *h.Element {
2 // Some expensive call
3 data := http.Get("https://api.example.com/data")
4 return h.Div(
5 h.Text(data),
6 )
7}
8
9var CachedComponent = h.CachedT(time.Minute*15, func(ctx *h.RequestContext) *h.Element {
10 return ExpensiveComponent(ctx)
11})
12
13func IndexPage(ctx *h.RequestContext) *h.Page {
14 return h.NewPage(
15 CachedComponent(ctx),
16 )
17}
We are using CachedT because the component takes one argument, the RequestContext.
If the component takes more arguments, use CachedT2, CachedT3, etc.
Important Note: When using h.CachedT and not CachedPerKey, the cached value is stored globally in memory, so it is shared across all requests.
Do not store request-specific data in a cached component. Only cache components that you are OK with all users seeing the same data.
The arguments passed into cached component DO NOT affect the cache key. You will get the same cached component regardless of the arguments passed in. This is different from what you may be used to from something like React useMemo.
Ensure the declaration of the cached component is outside the function that uses it. This is to prevent the component from being redeclared on each request.