useRef
.current
프로퍼티로 전달된 인자로 초기화된 변경 가능
한 ref 객체를 반환
Usage
ref를 통한 값 참조
- ref 값 변경 시 리렌더링을 유발하지 않음 → 화면에 업데이트 시키지 않음
- useState와 차이
- 리렌더링 후에도 유실없는 정보 저장 가능 (렌더링 때마다 초기화되는 일반 변수들과 차이)
let ref = useRef(0);
function handleClick() {
ref.current = ref.current + 1;
alert('You clicked ' + ref.current + ' times!');
}
return (
<button onClick={handleClick}>
Click me!
</button>
);
DOM 조작
- DOM 요소 선택하여 focus() 주기
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
유효기간
설정permanent cookie
session cookie