What are Hooks?
Hooks are functions that let you “hook into” GlyphUI features from functional components. They enable you to add state, side effects, and other capabilities to your components without writing classes. GlyphUI’s hooks system is inspired by React, providing a familiar and powerful API for managing component behavior.Available Hooks
GlyphUI provides the following built-in hooks:- useState - Add state to functional components
- useEffect - Perform side effects after rendering
- useRef - Create mutable references that persist across renders
- useMemo - Memoize expensive computations
- useCallback - Memoize callback functions
Rules of Hooks
To ensure hooks work correctly, you must follow these rules:Only Call Hooks from Functional Components
Hooks can only be called from within a functional component’s render function or from inside another custom hook. Don’t call them from:- Regular JavaScript functions
- Class components
- Event handlers outside of the render function
- Async callbacks after rendering
Only Call Hooks at the Top Level
Don’t call hooks inside loops, conditions, or nested functions. Always use hooks at the top level of your functional component, before any early returns. This ensures hooks are called in the same order every time a component renders, which is critical for maintaining internal state correctly.How Hooks Work
GlyphUI maintains a hooks store for each component instance using aWeakMap. When a component renders:
- The hooks system initializes with
initHooks(componentInstance) - Each hook call increments an internal hook index
- Hooks are stored in order and retrieved by index on subsequent renders
- After rendering completes,
finishHooks()is called
Error Handling
If you try to call a hook outside of a component’s render context, you’ll see this error:checkHooksContext() function in packages/runtime/src/hooks.js:84-92.
Example: Using Multiple Hooks
Here’s a complete example demonstrating multiple hooks working together:Next Steps
Explore each hook in detail:- Learn about useState for managing component state
- Use useEffect for side effects and lifecycle events
- Store mutable values with useRef
- Optimize performance with useMemo and useCallback