ReactJS 훅 패턴 ~UseImperativeHandle~
Source: Dev.to
useImperativeHandle는 자식 컴포넌트가 ref 를 통해 부모 컴포넌트에 특정 메서드를 노출하도록 허용합니다. 이 패턴은 입력에 포커스를 맞추는 등 자식 컴포넌트의 함수를 명령형으로 호출해야 할 때 유용합니다. useImperativeHandle는 전체 DOM 노드를 노출하지 않고, 대신 focusInner와 같은 특정 메서드만 노출할 수 있습니다.
예시
import { useRef, useImperativeHandle } from "react";
function CustomInput({ ref, ...rest }) {
const localRef = useRef();
useImperativeHandle(ref, () => ({
focusInner: () => {
localRef.current.focus();
},
}));
return ;
}
function App() {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focusInner();
};
return (
Focus Input
);
}
export default App;