egui_hooks
React Hooks like API for egui
Overview
This crate provids React Hooks like API for egui.
Though this started as a toy project, eventually I found that it's definitely
useful and that could be a core building block for both widget development and
application development. Managing UI states in UI side is the key in recent UI
development scene, but built-in egui::Memory
is relatively low-level API and
not friendly for applcation development, and egui_hooks provides a higher level
API but with more precise control.
Features
- No resource leak: Opposite to using
egui::Memory
directly, the states are automatically freed from the HashMap when the widget will be no longer displayed. This is based onTwoFrameMap
(2f kv) defined in this crate. - No locking nor callback: You can manage states without
ui.data(|| { ... })
. This is because hooks encapsulate the underlying RwLock. - Dependency tracking: Hooks has dependencies like
use_state(|| user_id.clone(), user_id)
oruse_effect(|| log(input), input)
, so you can precisely track the dependencies without manually writingif
statements on state change. - Composable: Hooks are composable, you can call existing hooks in your custom
hooks. For example,
use_state
internally usesuse_2f_kv
. - Familiar API: Hooks are designed to be similar to React Hooks API, so you can easily learn how to use them.
Status
-
use_memo
-
use_effect
-
use_effect_with_cleanup
-
use_state
,use_persisted_state
-
state.into_var()
to use state as a variable -
use_kv
,use_persisted_kv
-
use_2f_kv
,use_persisted_2f_kv
-
use_ephemeral_kv
-
use_global
,use_persisted_global
, anduse_ephemeral_global
-
use_cache
(a thin wrapper of caches inegui::Memory
) -
use_previous_area
-
use_measurement
(calculate the size of the widget without fear of the 2^N problem. -
use_future
(needstokio
feature) -
use_throttle
anduse_debounce
-
use_drag_origin
-
use_two_path
(it's joke, but really want to implement this)
Usage
- use_state
// You can reset the initial state by changing the dependency part.
let count = ui.use_state;
ui.label;
if ui.button.clicked
- use_memo
let count = ui.use_state;
let memo = ui.use_memo;
ui.label;
if ui.button.clicked
Custom Hooks
You can create your own hooks by the two ways.
- Creating a function for a hook
This is the simplest and recommended way to create a custom hook.
- Implement
Hook
trait
All built-in hooks are implemented in this way. This allow you to create a hook with full control, but it is a bit verbose.