https://react-ko.dev/reference/react/useImperativeHandle ref๋ก ๋ ธ์ถ๋๋ ํธ๋ค์ ์ฌ์ฉ์๊ฐ ์ง์ ์ ์ํ ์ ์๊ฒ ํด์ค๋ค.
useImperativeHandle(ref, createHandle, dependencies?)import { forwardRef, useImperativeHandle } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
useImperativeHandle(ref, () => {
return {
// ... ๋ฉ์๋๋ ์ฌ๊ธฐ์ ์์ฑํฉ๋๋ค ...
};
}, []);Parameters
ref:forwardRefํจ์์์ ๋๋ฒ์งธ์ธ์๋ก ๋ฐ์ ๊ฐ์ฒดcreateHandle: ๋ ธ์ถํ๋ ค๋ ref ํธ๋ค์ ๋ฐํํ๋ ํจ์. ์๋ฌด๋ฐ ์ ํ์ด๋ ๋ ์ ์์ผ๋, ์ผ๋ฐ์ ์ผ๋ก๋ ๋ ธ์ถํ๋ ค๋ ๋ฉ์๋๊ฐ ์๋ ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ค.dependencies(optional)createHandle์์ ์ฐธ์กฐํ๋ ๋ชจ๋ ๋ฐ์ํ ๊ฐ์ ๋์ด.- ๊ฐ ์์กด์ฑ์
Object.is๋ก ์ด์ ๊ฐ๊ณผ ๋น๊ตํ๊ณ , ๋ณ๊ฒฝ๋์์ผ๋ฉดcreateHandle์ ๋ค์ ์คํํ๊ณ ์ฌ์์ฑ๋ ํธ๋ค์ ref์ ํ ๋นํ๋ค.
Caveats
- ref๋ฅผ ๊ณผ๋ํ๊ฒ ์ฌ์ฉํ๋ฉด ์๋๋ค. props๋ก ํํํ ์ ์๋ ํ์์ ์ธ ํ๋์๋ง ์ฌ์ฉํด์ผํ๋ค.
- ex) scrollToView, focus, startAnimation, selecting textโฆ etc
- props๋ก ํํํ ์ ์๋ ๊ฒ์ ref๋ฅผ ์ฌ์ฉํ์ง๋ง๋ผ
- ex) ๋ชจ๋ฌ์์
open,close๋ฅผ ๋ ธ์ถํ๋ ๊ฒ๋ณด๋ค<Modal isOpen={isOpen}/>๊ณผ ๊ฐ์ดisOpenprop์ ์ฌ์ฉํ๋ ๊ฒ์ด ๋ ์ข๋ค.
- ex) ๋ชจ๋ฌ์์
Usage
Exposing a custom ref handle to the parent component
ref ํธ๋ค ์ค ๋ชจ๋ ๊ฒ์ ๋ถ๋ชจ์๊ฒ ๋
ธ์ถํ๊ณ ์ถ์ง ์์ ์๋ ์๋ค. ์ด๋ด๋ ๋ค์๊ณผ ๊ฐ์ด useImperativeHandle๋ฅผ ์ฌ์ฉํด์ ํ์ํ ๊ฒ๋ง ๋
ธ์ถ์ด ๊ฐ๋ฅํ๋ค.
import { forwardRef, useRef, useImperativeHandle } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => {
return {
focus() {
inputRef.current.focus();
},
scrollIntoView() {
inputRef.current.scrollIntoView();
},
};
}, []);
return <input {...props} ref={inputRef} />;
});Exposing custom imperative methods
import { forwardRef, useRef, useImperativeHandle } from 'react';
const CommentList = forwardRef(function CommentList(props, ref) {
const divRef = useRef(null);
useImperativeHandle(ref, () => {
return {
scrollToBottom() {
const node = divRef.current;
node.scrollTop = node.scrollHeight;
}
};
}, []);
return (
<div className="CommentList" ref={divRef}>
{props.comments}
</div>
);
});
export default CommentList;