Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

RenderOnce

The RenderOnce trait as opposed to the Render trait is used when you want to create a component instead of a view. As the name suggests they are only rendered once, they are constructed, rendered, and then dropped. This is the immediate mode of rendering which is done inside retained mode views.

Contrary to Render the render function of RenderOnce takes ownership of self unlike the mutable reference of self that Render supplies. This is useful for components that do not need to store any mutable application state.

Implementation

use gpui::{
    App, AppContext, Application, Context, IntoElement, ParentElement, Render, RenderOnce, Window,
    WindowOptions, div,
};

#[derive(IntoElement)]
struct SomeComponent;

impl RenderOnce for SomeComponent {
    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
        div()
    }
}

struct RootView;

impl Render for RootView {
    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
        div().child(SomeComponent)
    }
}

fn main() {
    Application::new().run(|app| {
        app.open_window(WindowOptions::default(), |_window, app| {
            app.new(|_cx| RootView)
        })
        .unwrap();
    });
}