The use_resource Hook
The use_resource hook is designed for fetching and managing asynchronous data. Unlike use_future, it returns a value that you can render in your UI.
Basic Usage
Resource States
A resource can be in one of four states:- Pending - The future is currently running
- Ready - The future completed successfully
- Paused - The future has been paused
- Stopped - The future was cancelled
Option<T> where:
None- The resource is still loadingSome(value)- The resource has completed and returned a value
Reactive Dependencies
One of the most powerful features ofuse_resource is automatic reactivity. The resource will automatically re-run when any signals read inside the future change:
Controlling the Resource
TheResource<T> handle provides several methods to control execution:
Methods
restart()- Cancel and restart the resource fetchcancel()- Stop the resource fetchpause()- Pause executionresume()- Resume a paused resourceclear()- Clear the value without stopping the taskstate()- Get the current statevalue()- Get a signal to the valuefinished()- Check if the resource is done loading
Reading Resource Values
There are several ways to read resource values:Direct Reading
Getting a Signal
Checking State
Working with Results
For resources that returnResult<T, E>, you can use the .result() method:
Practical Examples
User Profile with Refetch
Search with Debouncing
Multiple Dependent Resources
Server-Side Rendering
use_resource works with SSR and will serialize data for hydration:
Best Practices
- Handle All States - Always handle None, Ok, and Err cases
- Use Signals for Dependencies - Read signals inside the future for reactivity
- Debounce Frequent Updates - Add delays for rapid signal changes (like search)
- Clear Stale Data - Use
.clear()when appropriate - Error Handling - Always return
Resulttypes for robust error handling - Avoid Blocking - Never block the async runtime
- Loading States - Provide good UX with loading indicators
Differences from use_future
| Feature | use_resource | use_future |
|---|---|---|
| Returns value | ✅ Yes | ❌ No |
| Reactive | ✅ Yes | ❌ No |
| SSR Support | ✅ Yes | ❌ No |
| Use case | Data fetching | Background tasks |
| Value type | Option<T> | N/A |
Next Steps
- Learn about Suspense boundaries for better loading UX
- Understand Error handling patterns
- See use_future for background tasks