forwardRef in React — React Technical Interview Questions & Answers
forwardRef in React
forwardRef in React
- ref is not a normal prop. If you put ref={inputRef} on your own <Field />, Field won’t receive it unless you wrap with forwardRef. forwardRef((props, ref) => <input ref={ref} {...props} />) passes the ref to the real DOM node (or to another component that can take it).
- Parent then does inputRef.current.focus(). Useful for design-system inputs. React 19 eases some ref-as-prop cases — still know forwardRef; interviews love it.
- forwardRef in React — click Focus → name field focuses. Without forwardRef, ref on a custom component is ignored.
Technical Interview Tip: Why ref fails on custom components + forwardRef fix.
Code Examples for forwardRef in React
Example
// forwardRef
import { forwardRef, useRef } from "react";
const Field = forwardRef(function Field(props, ref) {
return <input ref={ref} {...props} />;
});
export default function Form() {
const name = useRef(null);
return (
<>
<Field ref={name} placeholder="Name" />
<button type="button" onClick={() => name.current.focus()}>
Focus
</button>
</>
);
}
forwardRef in React — click Focus → name field focuses. Without forwardRef, ref on a custom component is ignored.
How to Explain forwardRef in React to an Interviewer
Explain forwardRef as if you are teaching a junior — definition, then one tiny UI.
ref isn’t a regular prop. forwardRef(props, ref).
Write 5–10 lines that use forwardRef and say what the UI does.
Show JSX Say the screen
What mistake do freshers make with forwardRef?
parent focuses child input.