current 라는 객체에 저장됨
useRef 는 current 라는 속성을 가진 객체를 반환한다.
current 에 들어가는 값은 useRef 의 인자로 넘겨준 값이다. > 리렌더링이 되어도 계속 유지하기 위해서
컴포넌트의 DOM 요소에 접근하기 위해서
리액트에서는 document.queyrSelect ~ 이런식으로 dom 요소를 가져오는 것은 권장하지 않는다.
html 속성에는 ref 라는 값이 다 있음
리렌더링이 되는 조건
1. 부모에서 내려온 props 가 바뀌었을 때
2. 컴포넌트 내부의 state 가 변경이 생겼을 때
리렌더링이 되면 함수가 처음부터 다시 실행된다.
useRef 사용하면 손쉽게 dom 요소에 접근이 가능함.
useRef(value) 를 호출하면 ref Object 를 반환해준다
ref Object = {current:value}
우리가 value로 넣은 값은 current 에 저장이 됨
ref Object 는 언제든 수정가능
useRef 는 언제사용할까 ?
: ref 는 state 와 비슷하게 저장공간으로서의 역할을 한다. But !
ref 의 값들이 변화해도 재렌더링되지않고, 변수들의 값이 유지된다 => 불필요한 렌더링을 막을 수 있다
DOM 요소에 접근할 수 있다
- input 요소를 클릭하지않아도 자동적으로 focus 가 될 수 있게 해줌 => ref 사용하면 쉽게 구현가능
const ref = useRef(value)
<input ref ={ref}/>
※ 실습

Exam1.js
import React, { useRef, useState } from 'react';
const Exam1 = () => {
const refName = useRef();
const refAddress = useRef();
const [form, setForm] = useState({
name:'',
address:''
});
const {name, address} = form;
const onChangeInput = (e) => {
const nextForm = {
...form,
[e.target.name] : e.target.value
}
setForm(nextForm);
};
const onClickFocus = (e) => {
let nextForm
if(e.target.name === "name"){
refName.current.focus();
nextForm = {
...form,
[e.target.name] : '이름 입력'
};
} else if(e.target.name === "address"){
refAddress.current.focus();
nextForm = {
...form,
[e.target.name] : '주소 입력'
};
}
setForm(nextForm);
};
return (
<div>
<input type='text'
ref={refName}
name='name'
placeholder='이름 입력'
onChange={onChangeInput}
value={name}/>
<button onClick={onClickFocus} name='name'>
버튼1
</button>
<br/>
<input type='text'
ref={refAddress}
name='address'
placeholder='주소 입력'
onChange={onChangeInput}
value={address}/>
<button onClick={onClickFocus} name='address'>
버튼2
</button>
</div>
);
};
export default Exam1;
Exam2.js
import React, { useState } from 'react';
const Exam2 = () => {
const [pdName, setPdName] = useState();
const onChangePdName = (e) => {
setPdName(e.target.value);
};
const onClickChange = (e) => {
setPdName("상품명 입력");
}
return (
<div>
<input type='text'
name='pdName'
onChange={onChangePdName}
value={pdName}/>
<button onClick={onClickChange}>
버튼
</button>
</div>
);
};
export default Exam2;
App.js
import { useState } from 'react';
import './App.css';
import Exam1 from './components/Exam1';
import Exam2 from './components/Exam2';
function App() {
return (
<div>
<h1>실습</h1>
<Exam1/>
<hr/>
<Exam2/>
</div>
);
}
export default App;
'React' 카테고리의 다른 글
| [React] useEffect (0) | 2022.07.01 |
|---|---|
| [React] useConext + Context API (0) | 2022.06.30 |
| [React] useState (0) | 2022.06.28 |
| [React] import / export (0) | 2022.06.27 |
| [React] props / state (0) | 2022.06.24 |