useRef란 React에서 DOM에 접근하기 위해 사용하는 Hook이다.
import React, { useRef, useState } from 'react'
const Main = () => {
const inputRef = useRef(''); // ref 선언
const [data, setData] = useState('');
const focusInput = () => {
setData('');
inputRef.current.focus(); // dom 요소에 focus
};
return (
<div>
<input value={data} onChange={(e) => setData(e.target.value)} ref={inputRef} />
<button onClick={focusInput}>초기화</button>
</div>
);
}
export default Main
import React, { useRef, useState } from 'react'
import Children from './children'
const Parent = () => {
const [data, setData] = useState();
const ref = useRef(0);
const changeDataAndRef = (value) => {
setData(value);
ref.current += 1; // ref 값 업데이트
console.log("Parent ref current : " + ref.current)
}
return (
<div>
<h1>Parent Component Start</h1>
<input value={data || ''} onChange={(e) => changeDataAndRef(e.target.value)} />
<Children data={data} ref={ref} /> // ref 전달
<h1>Parent Component End</h1>
</div>
)
}
export default Parent
import React, { forwardRef, useEffect } from 'react'
const Children = forwardRef((props, ref) => {
useEffect(() => {
console.log("Children ref current : " + ref.current)
}, [props.data]) // 부모 컴포넌트로부터 받은 props가 변경될 때마다 리렌더링
return (
<div>
<h1>Children Component Start</h1>
{props.data}
<h1>Children Component End</h1>
</div>
)
})
export default Children
리렌더링 되어도 ref의 값이 유지되므로 Parent 컴포넌트의 input 입력 시 다음과 같이 콘솔이 출력된다.