Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Architecture and Setup

State Management in Rust with Tauri

Share application state across Tauri commands with manage() and State, protect it with Mutex or RwLock, choose between std and async mutexes, and see how it works.

Most apps remember something: a list of notes, a counter, an open database connection, user settings. In Tauri you keep such data in managed state: values you register once and then ask for from any command, event handler or window. This lesson shows how, and why Mutex appears everywhere.

Registering state

Rust
use std::sync::Mutex;

#[derive(Default)]
struct AppState {
    counter: u32,
    notes: Vec<String>,
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .manage(Mutex::new(AppState::default()))
        .invoke_handler(tauri::generate_handler![increment, add_note, list_notes])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

manage(...) stores one value per type. Registering two values of the same type panics, so wrap them in different structs if you need two.

Reading state in a command

A command asks for state by taking a State<T> parameter. Tauri fills it in:

Rust
use tauri::State;

#[tauri::command]
fn increment(state: State<'_, Mutex<AppState>>) -> u32 {
    let mut app = state.lock().unwrap();
    app.counter += 1;
    app.counter
}

#[tauri::command]
fn add_note(state: State<'_, Mutex<AppState>>, text: String) -> usize {
    let mut app = state.lock().unwrap();
    app.notes.push(text);
    app.notes.len()
}

#[tauri::command]
fn list_notes(state: State<'_, Mutex<AppState>>) -> Vec<String> {
    state.lock().unwrap().notes.clone()
}

The frontend never sees state; it is not an argument from JavaScript. Tauri injects it. The frontend just calls invoke('increment').

Why a Mutex?

Commands can run at the same time (several windows, rapid clicks, async commands on a thread pool). Rust refuses to share mutable data across threads unless access is synchronized. A Mutex allows one holder at a time: lock() waits for its turn and returns a guard; when the guard goes out of scope the lock is released.

State is already shared: Tauri holds it in an Arc internally, so you do not wrap your own value in Arc when you use manage. You only add Mutex (or RwLock) when the data changes.

Situation Wrap with
Never changes after startup (config, constants) nothing
Changes occasionally, many readers RwLock<T>
Changes often, simple access Mutex<T>
Held across .await in an async command tokio::sync::Mutex<T>
Single number or flag AtomicU32, AtomicBool

The await rule

Holding a std::sync::Mutex guard across an .await point can deadlock or fail to compile, because the guard cannot be sent between threads. Two safe habits:

  1. Lock, copy what you need, drop the guard, then await.
  2. Use an async-aware mutex from tokio::sync if you must hold it across awaits.
Rust
#[tauri::command]
async fn refresh(state: State<'_, Mutex<AppState>>) -> Result<usize, String> {
    let current = {
        let app = state.lock().unwrap();
        app.notes.len()            // guard dropped at the closing brace
    };
    // now it is safe to await something
    Ok(current)
}

Reaching state from elsewhere

Any type that implements Manager (the App, an AppHandle, a Window) offers state::<T>():

Rust
use tauri::Manager;

fn setup_hook(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
    let state = app.state::<Mutex<AppState>>();
    state.lock().unwrap().notes.push("welcome".into());
    Ok(())
}

You can also build state inside setup, which is useful when creating it needs the app handle (for example to find the data directory): call app.manage(...) there instead of on the builder.

Try it: Mutex and shared state in plain Rust

This runnable Rust example does not use Tauri, but it shows the same mechanism: shared state behind Arc<Mutex<...>>, mutated from several threads.

Rust Rust: shared counter behind a Mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Without the Mutex this would not compile; with it, the counter is always exactly 4000.

Try it: a state container with typed lookup (stand-in)

Tauri stores one value per type and returns it when a command asks for that type. This JavaScript stand-in imitates the registry and shows the "one per type" rule.

Node.js Stand-in: manage() and state()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Persisting state

Managed state lives in memory and vanishes on exit. To keep it, write it to disk (a JSON file in the app data directory, SQLite, or a store plugin) on change or on exit, and load it in setup. Later lessons cover the file system and the store plugin.

Common mistakes

  • Forgetting to manage a type: the command panics at runtime with a message about state not being managed. Add the manage call.
  • Using State<'_, AppState> when you registered Mutex<AppState>: the type must match exactly.
  • Holding a lock while doing slow work. Keep critical sections short.
  • Calling .lock().unwrap() twice on the same mutex in one scope: the second call deadlocks. Reuse the guard.

Next you will write real commands that use this state: Commands basics.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many values of the same type can you register with manage()?

    State is looked up by type, so registering the same type twice is an error.
  2. 2. Why is state usually wrapped in a Mutex?

    Mutex gives one-at-a-time access so concurrent commands cannot race.
  3. 3. What should you avoid when using a std Mutex in an async command?

    Drop the guard before awaiting, or use tokio::sync::Mutex.
  4. 4. Where does the frontend pass the state parameter from?

    State parameters are filled in by Tauri; only normal arguments come from invoke.

Summary

  • manage(value) registers one value per type; commands receive it as State<T>.
  • Wrap changing data in Mutex or RwLock; Tauri already shares state through an Arc.
  • Do not hold a std mutex guard across .await.
  • state::<T>() retrieves managed state from an App, AppHandle or window.
  • State is in memory only; persist explicitly if it must survive restarts.

Next: Commands basics