How to Create a Real-Time Dashboard Using Ratatui
Combine a tick-based loop with gauges, sparklines and bar charts to build a live dashboard that refreshes smoothly without wasting CPU.
Understand the split between rendering and input, read keys and mouse events safely on every platform, and keep crossterm versions aligned.

Ratatui draws your interface, but it does not read the keyboard, talk to the mouse or decide how the terminal is configured. Those jobs belong to a backend, and for most projects that backend is crossterm. Understanding where Ratatui ends and crossterm begins clears up a surprising number of bugs, from double key presses on Windows to type errors caused by two crossterm versions in one build. This guide explains the split, shows manual and automatic terminal setup, and walks through keyboard, mouse, resize and paste events with code that compiles against Ratatui 0.30.2.
Think of the two crates as layers. Ratatui owns layout, widgets, styled text and the double buffer that turns frames into minimal updates. crossterm owns the terminal itself: switching raw mode on and off, entering the alternate screen, moving the cursor, writing escape sequences and reading input events. Ratatui talks to crossterm through the Backend trait, implemented by CrosstermBackend in the ratatui-crossterm crate.
That division explains why event handling looks the same in every Ratatui tutorial: it is crossterm code. It also explains why Ratatui can support other backends such as termion, termwiz and termina without changing any widget. Your rendering code stays identical; only setup and input handling differ.
With default features, Ratatui depends on crossterm 0.29 and re-exports it as ratatui::crossterm. Importing from that path is the single most useful habit for Ratatui projects:
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};If you add crossterm to Cargo.toml yourself and Cargo picks a different version, you end up with two copies of the crate. Their types are not interchangeable, so code that passes an event from one into a function expecting the other fails with confusing "expected Event, found Event" errors. When you do need a direct dependency (for example to enable crossterm's event-stream feature), match the version Ratatui uses. Ratatui exposes crossterm_0_28 and crossterm_0_29 features so you can pick the version that matches the rest of your dependency tree.
cargo tree -i crossterm # who depends on crossterm, and which versions?
cargo tree -d # list every duplicated crateFor almost every app, ratatui::run() is all you need. It enables raw mode, enters the alternate screen, installs a panic hook that restores the terminal if your code panics, runs your closure and cleans up afterward. When you need more control, such as enabling mouse capture or bracketed paste, choosing an inline viewport or writing to stderr instead of stdout, you can perform the same steps with crossterm directly. Here is the manual version, equivalent to what Ratatui does for you plus mouse capture:
use std::io::{self, stdout};
use ratatui::backend::CrosstermBackend;
use ratatui::crossterm::event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode};
use ratatui::crossterm::execute;
use ratatui::crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::widgets::{Block, Paragraph};
use ratatui::Terminal;
fn main() -> io::Result<()> {
enable_raw_mode()?;
execute!(stdout(), EnterAlternateScreen, EnableMouseCapture)?;
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
let result = run(&mut terminal);
// Always restore, even if `run` returned an error.
disable_raw_mode()?;
execute!(stdout(), LeaveAlternateScreen, DisableMouseCapture)?;
terminal.show_cursor()?;
result
}
fn run(terminal: &mut Terminal<CrosstermBackend<io::Stdout>>) -> io::Result<()> {
loop {
terminal.draw(|frame| {
let p = Paragraph::new("Manual crossterm setup. Press q.").block(Block::bordered());
frame.render_widget(p, frame.area());
})?;
if let Event::Key(key) = event::read()? {
if key.code == KeyCode::Char('q') {
return Ok(());
}
}
}
}Notice the ordering: restoration happens after run returns, whatever its result, so an error does not leave the terminal in raw mode. This example does not install a panic hook, which is one reason the helpers are preferable. A middle ground is calling ratatui::init() for the standard setup and then enabling extras such as mouse capture with execute!, disabling them again before ratatui::restore().
In the terminal's normal "cooked" mode, input is buffered line by line, characters are echoed, and keys like Ctrl+C send signals to your process. Raw mode turns all of that off. Every key arrives immediately as an event, nothing is echoed, and Ctrl+C is just another key combination. That gives your app full control, but it also means you must implement quitting yourself, and you must restore cooked mode before exiting or the user's shell will behave strangely.
crossterm offers two ways to read input. event::read() blocks until an event is available, which is ideal when the screen only changes in response to the user. event::poll(timeout) waits up to a duration and returns whether an event is ready, which lets you run timers and animations between key presses.
A key event contains a code (such as KeyCode::Char('a'), KeyCode::Enter or KeyCode::F(5)), a set of modifiers (Shift, Control, Alt and others) and a kind. The kind is the detail people miss: on Windows, crossterm reports Press and Release events, and with enhanced keyboard protocols other platforms can report Repeat as well. Filtering for KeyEventKind::Press prevents every action from running twice.
A clean pattern is translating raw events into your own Action enum. The rest of your app then reacts to meaningful actions instead of key codes, which makes key bindings easy to change and test:
use std::time::Duration;
use ratatui::crossterm::event::{
self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEventKind,
};
enum Action {
Quit,
Up,
Down,
Click(u16, u16),
Resized(u16, u16),
Paste(String),
None,
}
fn next_action(timeout: Duration) -> std::io::Result<Action> {
if !event::poll(timeout)? {
return Ok(Action::None); // timed out: let the caller run a tick
}
Ok(match event::read()? {
Event::Key(key) if key.kind == KeyEventKind::Press => map_key(key),
Event::Mouse(m) => match m.kind {
MouseEventKind::Down(_) => Action::Click(m.column, m.row),
MouseEventKind::ScrollUp => Action::Up,
MouseEventKind::ScrollDown => Action::Down,
_ => Action::None,
},
Event::Resize(w, h) => Action::Resized(w, h),
Event::Paste(text) => Action::Paste(text),
_ => Action::None,
})
}
fn map_key(key: KeyEvent) -> Action {
match (key.code, key.modifiers) {
(KeyCode::Char('c'), KeyModifiers::CONTROL) | (KeyCode::Char('q'), _) => Action::Quit,
(KeyCode::Up, _) | (KeyCode::Char('k'), _) => Action::Up,
(KeyCode::Down, _) | (KeyCode::Char('j'), _) => Action::Down,
_ => Action::None,
}
}Mouse reporting is off by default because it changes how the terminal behaves: with capture enabled, the user can no longer select text with the mouse in the usual way. Enable it with execute!(stdout(), EnableMouseCapture) after setup and disable it with DisableMouseCapture before restoring. Mouse events report the kind (down, up, drag, moved, scroll), the button, the column and row, and modifiers.
To map a click to a widget, keep the Rect values computed during your last draw in state, then check whether the click position falls inside one of them with rect.contains(Position::new(column, row)). Because layout is recomputed every frame, store those rectangles after each draw so they always match what the user sees.
Event::Resize(width, height) arrives when the window changes size. Ratatui's draw automatically resizes its buffers, so you only need to handle this event if you cache size-dependent data.EnableBracketedPaste, pasted text arrives as a single Event::Paste(String) instead of a flood of key events, which is essential for text inputs.EnableFocusChange delivers FocusGained and FocusLost events, useful for pausing animations when the terminal is in the background.Terminal users bring habits from other tools, and matching them makes your app feel familiar immediately. Support q and Esc to quit or close, arrow keys plus j/k for vertical movement, Tab to move focus between panels, Enter to open or confirm, / to search and ? for help. Show the most important bindings in a footer or a block title so nobody has to guess. Keeping bindings in one table that maps keys to your Action enum also makes it easy to let users customize them through a configuration file later.
Apps built on Tokio often want to wait for input and network messages at the same time. crossterm provides an EventStream behind its event-stream feature, which you combine with tokio::select!. This requires a direct crossterm dependency with that feature, plus futures for StreamExt:
[dependencies]
ratatui = "0.30.2"
crossterm = { version = "0.29", features = ["event-stream"] }
futures = "0.3"
tokio = { version = "1", features = ["full"] }let mut events = crossterm::event::EventStream::new();
loop {
terminal.draw(|frame| ui(frame, &app))?;
tokio::select! {
Some(Ok(event)) = events.next() => app.handle_event(event),
Some(msg) = network_rx.recv() => app.handle_message(msg),
}
}Keep the crossterm version in this dependency identical to the one Ratatui uses (0.29 for Ratatui 0.30.2), or enable the matching crossterm_0_29 feature, so the event types line up.
Every setting you change must be reverted, in roughly the reverse order you applied it. If you enabled mouse capture, bracketed paste or focus reporting, disable them before leaving the alternate screen and turning off raw mode; otherwise the user's shell may keep receiving mouse escape codes. Put the cleanup in one function and call it from every exit path, including error returns. With ratatui::init() or ratatui::run() the panic hook restores raw mode and the alternate screen for you, but extra modes you enabled yourself still need your own cleanup, so disable them right after the main loop returns.
crossterm supports Windows, macOS and Linux from one codebase, but terminals differ. Windows Terminal handles colors, Unicode and mouse input well, while the legacy console host is more limited. On macOS, color depth varies between terminal apps. Inside tmux or screen, make sure true color and mouse support are enabled in the multiplexer configuration. If you need Unix-only features or a smaller dependency, the termion backend is an alternative on Linux and macOS, at the cost of Windows support.
No. It is a default feature of Ratatui and available as ratatui::crossterm. Add it directly only for extra crossterm features, and match the version Ratatui uses.
Raw mode delivers Ctrl+C as a key event instead of a signal. Match KeyCode::Char('c') with KeyModifiers::CONTROL and exit your loop normally.
Mouse capture is enabled. Terminals usually let users hold Shift (or Option on macOS) to select text anyway, or you can disable capture when it is not needed.
Yes, on Unix-like systems. Disable default features and enable termion plus all-widgets. Your widget code stays the same; setup and input code changes.
Yes for rendering: terminal.draw() resizes its buffers to the current size. Recompute layouts from frame.area() each frame and the interface adapts.
Ratatui and crossterm form a clean partnership: Ratatui renders, crossterm configures the terminal and delivers input. Import crossterm through ratatui::crossterm, prefer ratatui::run() for safe setup, filter key events by kind and translate raw events into your own actions. With those habits, input bugs become rare. Continue with our real-time dashboard tutorial to see poll in action, or read the official crossterm documentation for every event type and command.