Introduction to Bonsai
masterBonsai is a UI library for building performant, reactive web applications in OCaml. It is inspired by Elm and is designed around the concept of components implemented as purely functional state machines.
Key characteristics include:
- Incrementality: Values (including the view) are only recomputed when necessary, preventing unnecessary work.
- Composable State: Unlike frameworks that tie state to a UI component hierarchy, Bonsai allows you to compose state and incrementality primitives independently. This makes it easier to manage state lifecycles, such as embedding stateful components within tabbed interfaces without manual state hoisting.
- Full-stack OCaml: Enables sharing types and business logic between the backend and frontend.
module Dice = struct
let faces =
[ "⚀"; "⚁"; "⚂"; "⚃"; "⚄"; "⚅" ]
;;
let component (graph @ local) =
(* Components are implemented as purely functional state machines. *)
let face, set_face = Bonsai.state (List.hd_exn faces) graph in
(* Components are incrementally rendered, only when the relevant parts of the state change. *)
let%arr face and set_face in
{%html|
<div>
You rolled a #{face}
<button
style=""
on_click=%{fun _ ->
let index = Random.int (List.length faces) in
set_face (List.nth_exn faces index)}
>
Roll the dice
</button>
</div>
|}
";;