Imperative Handles
Sometimes a reusable component needs to expose a small imperative API, such as focus(), scrollToTop(), or open(). An imperative handle can expose a controlled interface instead of leaking internal DOM nodes.
Use this sparingly. Declarative props are usually easier to reason about. Imperative APIs are most appropriate for integration with inherently imperative behavior.
Exposing focus
useImperativeHandle(ref, () => ({
focus() {
inputRef.current?.focus();
}
}), []);💡 The parent receives a narrow imperative capability rather than direct access to internal implementation.
Key Takeaways
- Prefer declarative APIs when possible.
- Expose narrow imperative capabilities when integration requires them.
- Do not expose internal mutable state unnecessarily.