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}/>๊ณผ ๊ฐ™์ด isOpen prop์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋” ์ข‹๋‹ค.

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;