Futures in Dioxus
Dioxus provides excellent support for asynchronous programming, allowing you to run background tasks, fetch data, and handle long-running operations without blocking your UI.Understanding use_future
The use_future hook spawns a future that runs in the background. Unlike use_resource, it doesn’t return a value - it’s designed for side effects and background tasks.
Basic Usage
Key Characteristics
Non-Reactive
use_future is non-reactive - it runs once when the component is first rendered and continues until:
- The future completes
- The component is unmounted
- You manually cancel it
Client-Only Execution
Important:use_future does not run on the server. If you need server-side async execution, use dioxus_core::spawn_isomorphic directly.
Early Returns Pause Futures
When a component returns early (before reaching theuse_future hook), the future is automatically paused:
Controlling Future Execution
TheUseFuture handle gives you control over the future’s lifecycle:
Methods
restart()- Cancel the current future and spawn a new onecancel()- Forcefully stop the futurepause()- Temporarily pause executionresume()- Resume a paused futurefinished()- Check if the future has completedstate()- Get the current state (Pending, Paused, Stopped, or Ready)
Future States
A future can be in one of four states:- Pending - The future is currently running
- Paused - The future has been temporarily paused
- Stopped - The future has been forcefully cancelled
- Ready - The future has completed
Working with Streams
You can useuse_future with async streams to process data over time:
Async Event Handlers
You can also run async code directly in event handlers:Comparing with use_effect
use_effect is reactive and reruns when dependencies change:
When to Use use_future
Use use_future when you need to:
- Run a long-lived background task
- Start a task once on component mount
- Control task execution (pause/resume/cancel)
- Work with streams or continuous data sources
use_future when:
- You need to return and display data (use
use_resourceinstead) - You need reactivity to signals (use
use_effectinstead) - You need server-side rendering (use
use_resourceor server functions)
Best Practices
- Cleanup - Futures are automatically cancelled when the component unmounts
- Error Handling - Handle errors within your async block
- Signal Updates - Use signals to communicate results back to the UI
- Avoid Blocking - Never block the async runtime; use
.awaitproperly - Resource Cleanup - Clean up resources before the future exits
Next Steps
- Learn about use_resource for data fetching
- Understand Suspense for loading states
- Handle Errors in async code