Back to Blog

How to Share State Between Rust and React in Tauri

Sandy LaneSandy Lane

Video: How to Share State Between Rust and React in Tauri by Taught by Celeste AI - AI Coding Coach

Watch full page →

How to Share State Between Rust and React in Tauri

Managing shared state between Rust and React in a Tauri application enables you to build responsive desktop apps with synchronized backend logic and frontend UI. This tutorial demonstrates creating a thread-safe counter using Rust’s Mutex and tauri::State, then interacting with it from a React TypeScript frontend.

Code

use std::sync::Mutex;
use tauri::State;

// Define a thread-safe counter struct wrapping an integer in a Mutex
struct Counter(Mutex<i32>);

// Command to increment the counter
#[tauri::command]
fn increment(counter: State<Counter>) -> i32 {
  let mut count = counter.0.lock().unwrap();
  *count += 1;
  *count
}

// Command to decrement the counter
#[tauri::command]
fn decrement(counter: State<Counter>) -> i32 {
  let mut count = counter.0.lock().unwrap();
  *count -= 1;
  *count
}

fn main() {
  tauri::Builder::default()
    // Inject shared Counter state initialized at 0
    .manage(Counter(Mutex::new(0)))
    // Register commands callable from frontend
    .invoke_handler(tauri::generate_handler![increment, decrement])
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}

Key Points

  • Wrap shared state in a Rust Mutex to ensure thread-safe access across commands.
  • Use tauri::State to inject and share Rust state into command handlers.
  • Define #[tauri::command] functions to mutate and return updated state safely.
  • Call these Rust commands from React using Tauri’s invoke function to sync UI with backend state.
  • This pattern enables robust state management for desktop apps combining Rust and React.