Course contentsShow
← React
Lesson 2368 of 2,39651. TypeScript with React BasicsFree lesson

useImperativeHandle with Custom Types

Define custom ref handle interfaces when exposing imperative methods to parent components.

useImperativeHandle with Custom Types

You'll learn how to define a TypeScript interface for the imperative methods you expose to parent components through useImperativeHandle.

The Problem: Implicit "any" Refs

When you use useImperativeHandle to expose custom methods from a child component, the parent's ref doesn't automatically know what methods are available. Without explicit types, you lose TypeScript's safety and autocomplete.

The Solution: Define a Ref Handle Interface

Create an interface that describes exactly what methods your child exposes. This interface becomes the type argument to both forwardRef and useImperativeHandle:

// Define what the ref handle looks like
interface VideoPlayerHandle {
  play: () => void;
  pause: () => void;
  seek: (time: number) => void;
}

const VideoPlayer = forwardRef<VideoPlayerHandle, {}>((props, ref) => {
  useImperativeHandle(ref, () => ({
    play() {
      // implementation
    },
    pause() {
      // implementation
    },
    seek(time: number) {
      // implementation
    }
  }));

  return <div>Video Player</div>;
});

In the parent:

function App() {
  const playerRef = useRef<VideoPlayerHandle>(null);

  const handlePlay = () => {
    playerRef.current?.play(); // TypeScript knows about play()!
  };

  return <VideoPlayer ref={playerRef} />;
}

Think of It Like an API Contract

Your interface is a public API contract: "If you hold a ref to me, these are the methods I promise you can call, with these exact signatures."

Key Takeaway: Always define a named interface for useImperativeHandle's exposed methods and use it as the first type argument to forwardRef — this gives parents full type safety when calling imperative methods.