All topics
Hooksadvanced

useImperativeHandle and forwardRef

Learn how to expose a controlled imperative API from a child component to a parent via refs.

forwardRef lets a component accept a ref from its parent and forward it to one of its own internal elements or expose a custom object instead. By default, function components cannot receive a ref prop directly — forwardRef wraps the component to opt into that behavior explicitly.

It's like a hotel front desk (the imperative handle) that lets guests (the parent) ring a bell for specific services — room service, wake-up call — without handing them a master key to wander the building and rearrange furniture (the raw DOM) themselves.

Key Concepts

1
useImperativeHandle(ref, createHandle, deps) is used inside a forwardRef-wrapped component to customize exactly what the parent's ref will see, instead of exposing the raw DOM node. This lets you present a curated imperative API — like focus(), scrollToTop(), or reset() — while keeping the actual DOM structure and internal implementation private.
useImperativeHandle(ref, createHandle, deps)forwardReffocus()scrollToTop()reset()
2
This pattern is intentionally used sparingly, since React strongly favors a declarative, props-down data flow. It's reserved for genuinely imperative concerns that don't map well to props, such as triggering a focus, a scroll, an animation, or a form reset from a parent, where expressing 'please focus now' as a piece of state would be awkward.
3
Interviewers use this topic to see if a candidate can identify the narrow, legitimate use cases for imperative refs versus reaching for them out of habit when a simple prop or callback would express the same intent more declaratively.