→ 컴포넌트에서 특정 DOM 을 선택해야 할 때, 사용한다.
함수형 컴포넌트에서 ref를 사용할땐 useRef라는 Hook함수를 사용한다.
**useRef Hook은 컴포넌트 안에서 조회 및 수정할 수 있는 변수를 관리할때도 사용한다.**
**useRef**로 관리하는 변수는 값이 바뀐다고 해서 컴포넌트가 리렌더링되지 않는다. 리액트 컴포넌트에서의 상태는 상태를 바꾸는 함수를 호출하고 나서 그 다음 렌더링 이후 업데이트된 상태를 조회할 수 있지만, useRef로 관리하고 있는 변수는 설정 후 바로 조회할 수 있다.// App.js
import React from 'react';
import UserList from './UserList';
function App() {
const users = [
{
id: 1,
username: 'velopert',
email: 'public.velopert@gmail.com'
},
{
id: 2,
username: 'tester',
email: 'tester@example.com'
},
{
id: 3,
username: 'liz',
email: 'liz@example.com'
}
];
return <UserList users={users} />;
}
export default App;
// UserList.js
import React from 'react';
function User({ user }) {
return (
<div>
<b>{user.username}</b> <span>({user.email})</span>
</div>
);
}
function UserList({ users }) {
return (
<div>
{users.map(user => (
<User user={user} key={user.id} />
))}
</div>
);
}
export default UserList;
App.js
import React, { useRef } from 'react';
import UserList from './UserList';
function App() {
const users = [
{
id: 1,
username: 'velopert',
email: 'public.velopert@gmail.com'
},
{
id: 2,
username: 'tester',
email: 'tester@example.com'
},
{
id: 3,
username: 'liz',
email: 'liz@example.com'
}
];
**const nextId = useRef(4);
const onCreate = () => {
// 나중에 구현 할 배열에 항목 추가하는 로직
// ...
nextId.current += 1;
};**
return <UserList users={users} />;
}
export default App;
useRef를 사용할 때 파라미터를 넣어주면, 이 값이 .current의 기본값이 된다. 이 값을 수정할 땐 .current의 값을 수정하면 되고, 조회할 땐 .current를 조회하면 된다.