React Foundations ยท Effects & Refs

Exposing a custom ref handle

useImperativeHandle

Exposing a custom ref handle

A ref on a DOM element hands the parent the whole node. Usually that is more than you want to give away. Maybe the parent only needs to focus the input, not read every property on it. useImperativeHandle lets a component choose exactly what its ref exposes:

const TextInput = forwardRef((props, ref) => {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
  }));

  return <input ref={inputRef} />;
});

The parent passes a ref, and the child replaces its value with the object useImperativeHandle returns:

const handle = useRef(null);

<TextInput ref={handle} />;
handle.current.focus();

The parent can call focus, but it cannot reach the underlying <input>. The handle is the only surface the child offers, which keeps its internals private and its API deliberate.

useImperativeHandle is an escape hatch. Prefer props and state, and reach for it only when a parent genuinely needs to call a method on a child.

Your job is to expose a focus method through a ref handle in App.jsx.

Challenge

A Focus button should reach into a child input, and a plain ref will not do it. Export an App component from App.jsx that renders a TextInput child and a Focus button. The child forwards its ref with forwardRef and uses useImperativeHandle to expose a focus method that focuses the input. The button calls handle.current.focus().

The Test clicks your Focus button and expects the input to be the active element. The starter renders the input and button but wires up no handle, so the Test fails.

App.jsx
export function App() {
  return (
    <div>
      <input />
      <button>Focus</button>
    </div>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.