GPUI Hooks
For Chinese version, see README_zh.md
A Rust library that adds React-style Hook system to the GPUI framework.
Features
- React-style Hooks:
use_state,use_effect,use_memo - Attribute Macro:
#[hook_element]automatically adds Hook support to structs - Type Safety: Full Rust type system support
- Zero-cost Abstraction: Compile-time hook management, minimal runtime overhead
- GPUI Integration: Seamless integration with GPUI's
Rendertrait
Installation
Add to your Cargo.toml:
[]
= "0.1"
Note: This library requires the GPUI framework.
Quick Start
1. Create a Hook Component
use ;
use ;
use ;
2. Run the Application
3. Run Example
API Documentation
Hooks
use_state
Manages component state.
let = self.use_state;
- Parameters: Closure returning initial value
- Returns:
(getter, setter)tuple - Type Constraint:
T: Clone + 'static
use_effect
Executes side effects.
self.use_effect;
- Parameters:
deps: Dependency array, re-executes when dependencies changeeffect: Side effect closure, returns optional cleanup function
- Note: Components must call
cleanup_effects()in theirDropimplementation
use_memo
Memoizes computed values.
let memoized = self.use_memo;
- Parameters:
deps: Dependency array, re-computes when dependencies changecompute: Computation closure
- Returns:
getterfunction returning memoized value
Macro
#[hook_element]
Attribute macro that automatically adds Hook support to structs.
The macro automatically:
- Adds
_hooks,_hook_index,_prevfields - Implements
Defaulttrait - Implements
HookedElementtrait - Implements
gpui::Rendertrait
Traits
HookedElement
Basic trait for hook components, providing hook management functionality.
HookedRender
Extends gpui::Render with hook lifecycle management.
Hook Rules
1. Only Call Hooks at the Top Level
❌ Wrong example:
if condition
✅ Correct example:
let = self.use_state;
if condition
2. Keep Hook Call Order Consistent
Each render must call the same number of hooks in the same order.
3. Manually Clean Up Effects
Components using use_effect must clean up in their Drop implementation:
Advanced Usage
Custom Hooks
Create reusable custom hooks:
Combining Multiple Hooks
Development Guide
Build Project
Run Tests
Code Quality
View Documentation
Contributing
Contributions are welcome! Please see CONTRIBUTING.md (to be created).
- Fork the project
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License. See the LICENSE file for details.
Acknowledgments
Contact
For questions or suggestions, please:
- Submit an Issue
- Join the discussion
Happy Hooking! 🎣