Both hooks deal with refs in React, but their purpose differs:
- useRef: Provides a mutable object to access DOM elements or store values.
- useImperativeHandle: Customizes the instance value exposed to parent when using
forwardRef.
useRef Example
import React, { useRef } from "react";
function Input() {
const inputRef = useRef();
return (
<div>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
</div>
);
}
✅ Access DOM element directly within the component.
useImperativeHandle Example
import React, { useRef, forwardRef, useImperativeHandle } from "react";
const Child = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focusInput: () => inputRef.current.focus()
}));
return <input ref={inputRef} type="text" />;
});
function App() {
const childRef = useRef();
return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.focusInput()}>Focus Input</button>
</div>
);
}
✅ Parent can call custom method on child using useImperativeHandle.
Key Differences
| Feature | useRef | useImperativeHandle |
|---|---|---|
| Purpose | Access DOM or store values | Customize child instance ref |
| Scope | Within component | Across parent-child |
| Requires forwardRef? | No | Yes |
| Use Case | Input focus, timers, mutable ref | Expose custom child methods |
Conclusion
Use useRef for direct DOM access, and useImperativeHandle to expose custom methods from child components.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP