forwardRef() in React is used to pass a ref from a parent component to a child component, allowing the parent to directly access the DOM element or React component instance inside the child.
⚙️ Why Use It:
Normally, refs don’t automatically pass through custom components.forwardRef() enables this by forwarding the ref down to a specific child DOM element.
💡 Example:
import React, { forwardRef, useRef } from "react";
const InputField = forwardRef((props, ref) => {
return <input ref={ref} type="text" placeholder="Type here..." />;
});
export default function App() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus(); // parent can access input element
};
return (
<div>
<InputField ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
📘 Key Points:
forwardRefis a higher-order function.- Useful when building reusable input components or wrapping UI libraries.
- Can be combined with
useImperativeHandle()for custom ref handling.
🧩 In Short:
forwardRef()lets parent components access a child’s DOM node or component instance directly by forwarding refs through component boundaries.