useImperativeHandle: Custom Instance Values
Use useImperativeHandle to control exactly what a parent sees when it holds a ref to your component.
The Default Forwarded Ref
When you forward a ref straight onto a DOM element, the parent receives that raw DOM node and gains access to every native method and property on it. That is often more surface area than you want to expose.
Sometimes you would rather hand the parent a small, curated object instead of the full DOM node, keeping the public API of your component deliberately narrow.
useImperativeHandle Replaces the Ref Value
useImperativeHandle lets you customize the value that the parent ref points to. Instead of the DOM node, the parent receives whatever object you return, so you decide exactly which methods and values are exposed.
This turns the forwarded ref into a defined imperative interface rather than a leaky pass-through to the underlying element.
All lessons in this course
- forwardRef: Exposing DOM Refs to Parents
- useImperativeHandle: Custom Instance Values
- Building an Imperative Component API
- When to Use Imperative vs Declarative APIs