Both Refs and Forward Refs are used to access DOM elements, but they have different use cases:
- Refs: Used inside a component to access its own DOM element.
- Forward Ref: Allows a parent component to pass a ref to a child component.
Ref 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 within the same component.
Forward Ref Example
import React, { useRef } from "react";
const Input = React.forwardRef((props, ref) => <input ref={ref} />);
function App() {
const inputRef = useRef();
return (
<div>
<Input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
</div>
);
}
✅ Parent can access child input element using Forward Ref.
Key Differences
| Feature | Refs | Forward Ref |
|---|---|---|
| Usage | Access component’s own DOM | Pass ref from parent to child |
| Scope | Inside the same component | Across components |
| Purpose | Direct DOM access | Parent control of child DOM |
| Component Type | Any component | Functional child components |
Conclusion
Use Refs for internal DOM access, and Forward Ref when the parent needs to interact with the child’s DOM element.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP