Что такое useImperativeHandle

Ответ

useImperativeHandle — это хук React, который позволяет кастомизировать экземпляр компонента, доступный через ref. Он полезен, когда родительскому компоненту нужно напрямую вызывать методы дочернего компонента.

Пример:

import { forwardRef, useImperativeHandle, useRef } from 'react';

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

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

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

function ParentComponent() {
  const childRef = useRef();

  return (
    <>
      <ChildComponent ref={childRef} />
      <button onClick={() => childRef.current.focus()}>Focus</button>
      <button onClick={() => childRef.current.clear()}>Clear</button>
    </>
  );
}

Нюансы:

  • Работает только с forwardRef.
  • Не злоупотребляйте им — нарушает инкапсуляцию.
  • Альтернатива — подъем состояния или колбэки.