useRef는 렌더링에 필요하지 않은 값을 참조할 수 있게 해주는 React Hook
import { useRef } from 'react';
const ref = useRef(initialValue);
useRef: 단일 프로퍼티(current)를 가진 객체를 반환한다.
initialValue : 참조 객체의 프로퍼티인 current에 처음에 지정할 값이다.
function MyComponent() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
// ...
return <input ref={inputRef} />;
}
current initialValue: 처음에는 전달한 것으로 설정된다.
나중에 다른 것으로 설정할 수 있다.
만약 참조 객체를 JSX 노드의 속성인 ref에 넣어 React에 전달하면
React가 해당 current속성을 설정한다.(DOM제어)
<input ref={inputRef} />
import { useRef } from 'react';
function Stopwatch() {
const intervalRef = useRef(0);
// ...
function handleStartClick() {
intervalRef.current = setInterval(() => {
// ...
}, 1000);
}
function handleStopClick() {
clearInterval(intervalRef.current);
}
}
import { useRef } from 'react';
export default function Counter() {
let ref = useRef(0);
function handleClick() {
ref.current += 1
alert('You clicked ' + ref.current + ' times!');
}
return (
<button onClick={handleClick}>
Click me!
</button>
);
}
랜더링하는동안 ref.current를 쓰거나 읽지 말기!
function MyComponent() {
// ...
// 🚩 Don't write a ref during rendering
myRef.current = 123;
// ...
// 🚩 Don't read a ref during rendering
return <h1>{myOtherRef.current}</h1>;
}
function MyComponent() {
// ...
useEffect(() => {
// ✅ You can read or write refs in effects
myRef.current = 123;
});
// ...
function handleClick() {
// ✅ You can read or write refs in event handlers
doSomething(myOtherRef.current);
}
// ...
}
ref를 이용해 DOM을 조작하는 것이 일반적이다.
import { useRef } from 'react';
export default function Form() {
//1. 먼저, 초기값을 갖는 참조 객체를 선언
const inputRef = useRef(null);
function handleClick() {
// 3. React는 ref 객체의 current속성을 <input>노드로 설정한다.
// 4. js함수인 focus()를 사용해 <input>노드를 focus 시킬 수 있다.
inputRef.current.focus();
}
return (
<>
//2. 조작하려는 DOM 노드의 JSX에 대한 속성 으로 참조 객체를 전달
<input ref={inputRef} />
<button onClick={handleClick}>
Focus the input
</button>
</>
);
}
forwardRef참조를 통해 구성 요소가 부모 구성 요소에 DOM 노드를 노출할 수 있다.
const SomeComponent = forwardRef(render)
ex.1)
const MyInput = forwardRef(function MyInput(props, ref) {
const { label, ...otherProps } = props;
return (
<label>
{label}
<input ref={ref} {...otherProps} />
</label>
);
});
ex.2)
const MyInput = forwardRef(function MyInput({label,result},ref) {
return (
<label>
{label}
<input ref={ref} />
</label>
);
});
function Form() {
const ref = useRef(null);
function handleClick() {
ref.current.focus();
}
return (
<form>
<MyInput label="Enter your name:" ref={ref} />
<button type="button" onClick={handleClick}>
Edit
</button>
</form>
);
}
즉 fowardRef를 사용하면 부모 컴포넌트에서 자식컴포넌트로 참조를 전달하여 자식 컴포넌트의 DOM노드를 참조하여 통제할 수 있는 기능이다.