🔰

TypeScriptでuseImperativeHandleを使う

に公開

useImperativeHandleのドキュメントを読んでいて、TypeScriptでどう書くか迷ったのでメモです。

https://ja.react.dev/reference/react/useImperativeHandle

結論

React19ではRefObjectに渡す型をPickしてあげると良さそう。

type FormProps = {
  ref: RefObject<Pick<HTMLInputElement, "focus"> | null>;
};

export const Form = ({ ref }: FormProps) => {
  const inputRef = useRef<HTMLInputElement>(null);
  useImperativeHandle(
    ref,
    () => ({
      focus: () => {
        if (inputRef.current) {
          inputRef.current.focus();
        }
      },
    }),
    [],
  );
  return <input ref={inputRef} className="border" />;
};

export default function Home() {
  const ref = useRef<Pick<HTMLInputElement, "focus">>(null);
  return (
    <>
      <Form ref={ref} />
      <button
        onClick={() => {
          ref.current?.focus();
        }}
        type="button"
      >
        Focus
      </button>
    </>
  );
}

useImperactiveHandleを使うことでfocusのみ呼び出すことができている。

Discussion