How to Build Your First Terminal Application with Ratatui

Set up a Cargo project, draw your first widgets, react to key presses and exit cleanly, with a complete counter app you can extend.

TutorialsRatatui Editorial Team8 min read
How to Build Your First Terminal Application with Ratatui featured image

Building a terminal user interface sounds intimidating until you see how little code it takes. In this tutorial you will create your first Ratatui application from an empty folder: a small counter app that draws a bordered panel, reacts to the keyboard and exits without leaving your shell in a broken state. Along the way you will learn the three ideas every Ratatui program is built on: the terminal lifecycle, immediate-mode drawing and an event loop that you control.

Everything here was compiled and run with Ratatui 0.30.2 and Rust 1.97. If you only want the shortest path to a running program, the installation section on our homepage has a condensed version. This article explains the why behind each line.

What You Will Build

By the end you will have a program that fills the terminal with a rounded panel, shows a number in the middle and lists its key bindings along the bottom border. Pressing the left and right arrow keys changes the number, and pressing q quits. It is deliberately small, but the structure (a state struct, an input handler and a render function) is the same one used by large dashboards and file managers.

Prerequisites

  • Rust 1.88.0 or newer. Ratatui 0.30.2 declares this as its minimum supported Rust version. Check yours with rustc --version and upgrade with rustup update.
  • A real terminal. Windows Terminal, iTerm2, GNOME Terminal, Alacritty, Kitty or WezTerm all work. Some IDE "run" panes are not true terminals and cannot enter raw mode, so launch the program from a terminal window.
  • Basic Rust knowledge. You should be comfortable with structs, impl blocks, match and the ? operator.

Step 1: Create the Project

Cargo generates a binary crate for you. Adding Ratatui with cargo add writes the newest compatible version into Cargo.toml together with the default features, which include the crossterm backend that works on Windows, macOS and Linux.

Terminal
cargo new counter-tui
cd counter-tui
cargo add ratatui

There is no need to add crossterm separately. Ratatui re-exports it as ratatui::crossterm, and importing from that path guarantees that the event types you use match the version Ratatui was built with. Mismatched crossterm versions are one of the most common beginner errors, so this habit saves time later.

Step 2: Understand the Terminal Lifecycle

A normal command-line program prints lines and lets the terminal handle input. A TUI needs more control, so it changes two terminal settings when it starts:

  • Raw mode delivers every key press to your program immediately, without waiting for Enter and without echoing characters to the screen.
  • The alternate screen is a separate buffer, similar to how editors like Vim take over the window. When your program exits, the terminal switches back and the user's previous output reappears untouched.

Both settings must be undone when the program ends, including when it panics. Forgetting this leaves the shell without echo, which is confusing for users. Ratatui solves it with ratatui::run(): you pass a closure that receives a ready-to-use terminal, and Ratatui enables raw mode, enters the alternate screen, installs a panic hook, runs your closure and restores everything afterward. If you need code between setup and teardown, the lower-level pair ratatui::init() and ratatui::restore() does the same job in two calls.

Step 3: Draw Your First Frame

Replace the contents of src/main.rs with the program below. It draws a bordered block containing a centered greeting and waits for q.

src/main.rs
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::widgets::{Block, Paragraph};
use ratatui::{DefaultTerminal, Frame};

fn main() -> std::io::Result<()> {
    ratatui::run(app)
}

fn app(terminal: &mut DefaultTerminal) -> std::io::Result<()> {
    loop {
        terminal.draw(render)?;
        if let Event::Key(key) = event::read()? {
            if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
                return Ok(());
            }
        }
    }
}

fn render(frame: &mut Frame) {
    let block = Block::bordered().title(" Hello Ratatui ");
    let greeting = Paragraph::new("Hello, World! Press q to quit.")
        .centered()
        .block(block);
    frame.render_widget(greeting, frame.area());
}

Run it with cargo run. In a 44-column, 5-row terminal the output looks like this:

Expected output
┌ Hello Ratatui ───────────────────────────┐
│      Hello, World! Press q to quit.      │
│                                          │
│                                          │
└──────────────────────────────────────────┘

Three details are worth noticing. First, terminal.draw() takes a function that receives a Frame; everything you render inside it becomes the next screen. Second, frame.area() returns a Rect covering the whole terminal, so the block resizes automatically when the window changes. Third, the program checks KeyEventKind::Press. On Windows, crossterm reports both key presses and key releases, and without this check every key would be handled twice.

Step 4: Add Application State

Ratatui uses immediate-mode rendering. It does not remember widgets between frames; instead, your program keeps the data and rebuilds the interface from it every time it draws. That makes the screen a pure function of your state, which is easy to reason about and easy to test.

For the counter, the state is a number and a flag that says whether the user asked to exit. Putting both in a struct gives you a natural home for methods that update and render it:

src/main.rs
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind};
use ratatui::layout::Alignment;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::{Block, Paragraph};
use ratatui::{DefaultTerminal, Frame};

#[derive(Default)]
struct App {
    counter: i64,
    exit: bool,
}

impl App {
    fn run(&mut self, terminal: &mut DefaultTerminal) -> std::io::Result<()> {
        while !self.exit {
            terminal.draw(|frame| self.render(frame))?;
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    self.handle_key(key);
                }
            }
        }
        Ok(())
    }

    fn handle_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Left | KeyCode::Char('j') => self.counter -= 1,
            KeyCode::Right | KeyCode::Char('k') => self.counter += 1,
            KeyCode::Char('q') | KeyCode::Esc => self.exit = true,
            _ => {}
        }
    }

    fn render(&self, frame: &mut Frame) {
        let instructions = Line::from(vec![
            " Decrement ".into(), "<Left>".blue().bold(),
            " Increment ".into(), "<Right>".blue().bold(),
            " Quit ".into(), "<Q> ".blue().bold(),
        ]);
        let block = Block::bordered()
            .title(Line::from(" Counter App ".bold()).centered())
            .title_bottom(instructions.centered());
        let text = Line::from(vec!["Value: ".into(), self.counter.to_string().yellow()]);
        let paragraph = Paragraph::new(text)
            .alignment(Alignment::Center)
            .block(block);
        frame.render_widget(paragraph, frame.area());
    }
}

fn main() -> std::io::Result<()> {
    ratatui::run(|terminal| App::default().run(terminal))
}

The render method builds a Block with a centered title and a bottom title made of styled spans. The Stylize trait adds shortcuts such as .bold(), .blue() and .yellow() to strings, so you can express styling inline without constructing Style values by hand. The paragraph inside the block shows the current value, and because the closure passed to ratatui::run() returns the result of App::run, any I/O error propagates cleanly out of main.

Step 5: Handle Keyboard Events

Input does not come from Ratatui; it comes from the backend. With crossterm, event::read() blocks until something happens and returns an Event: a key press, a mouse action, a paste, a focus change or a resize. The counter only cares about key presses, so handle_key matches on key.code and ignores everything else.

Blocking on read() is perfect for apps that only change when the user does something, because the process uses no CPU while waiting. If your interface must update on a timer (a clock, a progress bar or live metrics), switch to event::poll(timeout), which returns after the timeout even without input. Our real-time dashboard tutorial shows that pattern in depth, and the Ratatui and crossterm guide covers modifiers, mouse capture and paste events.

Raw mode disables the terminal's own Ctrl+C handling, so Ctrl+C arrives as a normal key event. If you want it to quit, match KeyCode::Char('c') together with KeyModifiers::CONTROL.

Step 6: Structure the Code as It Grows

A single file is fine for a counter, but real projects benefit from a predictable layout. A common structure separates state, input and drawing:

Suggested layout
src/
├── main.rs     // ratatui::run(...) and error handling
├── app.rs      // App struct, state transitions, key handling
├── ui.rs       // render functions and layout
└── widgets/    // custom widgets, one file each

Keep rendering code free of side effects: it should read state and draw, never modify state or perform I/O. Keep input handling free of drawing: it should translate events into state changes. This separation makes it simple to add features such as undo, configurable key bindings or a help popup later. It also lets you test state transitions without a terminal at all.

Step 7: Test the Interface

Because the screen is derived from state, you can render into an in-memory backend and compare the result with expected text. Implementing Widget for a reference to your app (&App) is an idiomatic way to make it renderable without consuming it. The example below compiles as a standalone file and its test passes with cargo test:

Snapshot-style test
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::{Block, Paragraph, Widget};

struct App {
    counter: i64,
}

impl Widget for &App {
    fn render(self, area: Rect, buf: &mut Buffer) {
        Paragraph::new(format!("Value: {}", self.counter))
            .centered()
            .block(Block::bordered().title(" Counter "))
            .render(area, buf);
    }
}

fn main() {}

#[test]
fn shows_counter_value() {
    let app = App { counter: 7 };
    let mut buf = Buffer::empty(Rect::new(0, 0, 18, 3));
    (&app).render(buf.area, &mut buf);
    let expected = Buffer::with_lines([
        "┌ Counter ───────┐",
        "│    Value: 7    │",
        "└────────────────┘",
    ]);
    assert_eq!(buf, expected);
}

Tests like this catch layout regressions immediately, for example when a refactor accidentally changes alignment or truncates a title. For larger apps, compare only the areas you care about, or use a snapshot-testing crate to store expected buffers as files.

Common Beginner Mistakes

  • Printing with println!. Writing to stdout while the TUI is active corrupts the screen. Log to a file, or show messages inside a widget instead.
  • Calling draw several times per loop. Render the whole interface in one draw call per iteration; split the work into helper functions that all receive the same Frame.
  • Using a separate crossterm dependency. Import events from ratatui::crossterm unless you need crossterm features Ratatui does not enable.
  • Exiting with std::process::exit. It skips cleanup. Return from your loop instead so the terminal is restored.
  • Running inside an IDE console. If you see "not a terminal" errors, launch the binary from a real terminal window.

If something still goes wrong, our troubleshooting guide lists the most frequent compiler and runtime errors with fixes.

Frequently Asked Questions

No. crossterm is enabled by default and re-exported as ratatui::crossterm. Add a direct dependency only when you need crossterm features that Ratatui does not turn on, and then keep the versions aligned.

ratatui::run() sets up the terminal, runs your closure and restores the terminal in one call. ratatui::init() returns the terminal so you can run code between setup and teardown, but you must call ratatui::restore() yourself.

Windows reports key releases as well as presses. Check key.kind == KeyEventKind::Press before handling a key event to process each key once.

Yes, in VS Code's integrated terminal, which is a real terminal. The debug console and some "Run" output panes are not, so start the program from the terminal panel.

Replace the blocking event::read() with event::poll(timeout). When poll returns false, the timeout elapsed and you can update time-based state before drawing again.

Conclusion

You now have a working Ratatui application and, more importantly, a mental model that scales. ratatui::run() manages the terminal lifecycle, your App struct owns state, an event loop translates input into state changes and a render function rebuilds the screen from that state on every frame. From here, try adding a second panel with layout constraints, replace the paragraph with a list or table from the widgets reference, or browse more complete programs on our examples page. The official Ratatui tutorials and the API documentation are excellent companions as your app grows.

Ratatui Editorial Team

We write tested guides for Rust developers building terminal user interfaces. Every code sample in this article was compiled against Ratatui 0.30.2. Spotted an issue? Let us know.