react.js
[react 리액트] useRef 언제 쓰나요? (react hook)
코복이
2023. 6. 14. 12:10
728x90

1. useRef 란?
리액트 Hook으로 State 처럼 값을 저장하는 공간인데 값이 바껴도 랜더링을 안 함
2. 선언
import { useRef } from 'react'
const 변수이름 = useRef(초기값)
3. 값(value)는 어떻게 뽑아다 쓰나요?
변수이름.current 를 가져다 쓰면 됨.
*ref는 current 라는 프로퍼티에 저장을 함.

4. useRef는 언제 쓰나요?
결론: 변화는 감지해야하지만 그 변화가 랜더링을 발생시키면 안되는 값을 다룰 때
1) 값 변경시 랜더링을 하면 안되거나 랜더링이 필요 없거나 너무 자주 랜더링이 될 것 같은 경우
*state는 값이 변화할 때마다 새로 랜더링
*ref에서 값이 변화해도 랜더링하지 않음.

2) 값을 전 생애주기로 유지시킬 때 (랜더링되어도 값이 유지)
*마운트 ~ 언마운트 까지 유지
*일반 변수는 랜더시, 초기값으로 리턴하는데 ref는 유지

5. 예제
input에 입력값을 받을때 useState를 쓰면 입력값이 바뀔때마다 랜더링을 새로하는 비효율이 있다.
useRef로 대체하면 값은 추적하지만 랜더링은 하지 않음.
* input에 ref 프로퍼티를 추가하고 내가 지정한 useRef를 넣어주면 추적함.
* 보통 이벤트핸들러로 target.event.value로 현재값을 가져오는데 ref 는 ref.current.value 로 가져옴.
function AddMovie(props) {
const titleRef = useRef('');
const openingTextRef = useRef('');
const releaseDateRef = useRef('');
function submitHandler(event) {
event.preventDefault();
// could add validation here...
const movie = {
title: titleRef.current.value,
openingText: openingTextRef.current.value,
releaseDate: releaseDateRef.current.value,
};
props.onAddMovie(movie);
}
return (
<form onSubmit={submitHandler}>
<div className={classes.control}>
<label htmlFor='title'>Title</label>
<input type='text' id='title' ref={titleRef} />
</div>
<div className={classes.control}>
<label htmlFor='opening-text'>Opening Text</label>
<textarea rows='5' id='opening-text' ref={openingTextRef}></textarea>
</div>
<div className={classes.control}>
<label htmlFor='date'>Release Date</label>
<input type='text' id='date' ref={releaseDateRef} />
</div>
<button>Add Movie</button>
</form>
);
}
728x90