React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
Is ref argument available for all functions or class components?
mid LevelCode ExampleComponentsHooks
Regular function or class components don’t receive the ref argument, and ref is not available in props either. The second ref argument only exists when you define a component with React.forwardRef call.
Code Example
tsx
import React, { forwardRef, useRef } from 'react';
// ❌ Regular function components do NOT receive the ref argument
function RegularInput(props: { label: string }) {
// props.ref is undefined and causes a React warning
return <label>{props.label} <input /></label>;
}
// ✅ forwardRef wraps the component to expose the second `ref` parameter
export const ExposeRefInput = forwardRef<HTMLInputElement, { label: string }>(
(props, ref) => {
return (
<label className="flex flex-col gap-1">
<span>{props.label}</span>
<input ref={ref} className="border p-2 rounded" />
</label>
);
}
);