Refs & forwardRefAdvanced
1Question 1 of 1
javascriptHow do useRef and forwardRef work in React?
Explanation & Concept
• `useRef`: Returns a mutable ref object whose `.current` property persists across renders without triggering a re-render when mutated. Used to hold DOM references or timers. • `forwardRef`: Allows a parent component to pass a ref down into a child functional component's internal DOM node.
Code Example
javascript
import { forwardRef, useRef } from "react";
// Child component exposing internal input ref to parent
const CustomInput = forwardRef((props, ref) => {
return <input ref={ref} className="border p-2" {...props} />;
});
CustomInput.displayName = "CustomInput";
export function ParentForm() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current?.focus(); // Direct DOM access
};
return (
<div>
<CustomInput ref={inputRef} placeholder="Type here..." />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}How It Works & Key Takeaways
`forwardRef` is essential when building reusable UI design system primitives like custom inputs, buttons, and modals.
Mock Test · 1 Questions · Optional
Ready for Suspense & Lazy Loading?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions