> For the complete documentation index, see [llms.txt](https://shhn0509.gitbook.io/react/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shhn0509.gitbook.io/react/react-study/hook/useref.md).

# useRef()

## 1. 언제 사용할까?&#x20;

* `useRef()`는 실제 DOM 노드를 참조 하여 참조 대상을 변경할 때 사용한다. `.current` 속성에 참조된 요소가 담겨있기 때문에 이 속성을 사용해서 요소에 접근하면 된다.&#x20;
* 이전의 상태 값을 기억하여 이전 값과 이후 값을 비교할 때 사용한다. →JS의 클로저 기능을 리액트에서 사용하고 싶을 때 사용한다.&#x20;

## 2. 용도&#x20;

### 2.1 상태를 기억&#x20;

`useRef()`는 `.current` 속성에 변경 가능한 값을 담고 있는 “상자”와 같다.&#x20;

```javascript
const refContainer = useRef(initialValue);
```

![클로저와 같이 이전의 값을 기억한다. ](https://831271375-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MSRg9KgNRIGErVFy_6g%2F-MWN2LgP6GuPAEOWeqHO%2F-MWN46U0tqI08lXN5HNE%2Fimage.png?alt=media\&token=a1b5b200-c1d5-42a9-9dae-2ad6e6deccd7)

{% hint style="warning" %}
위의 이미지 코드는 이해를 돕기 위한 이미지이다. 실제로 작동하지 않는다.&#x20;
{% endhint %}

### &#x20;2.2 DOM 객체 참조&#x20;

&#x20;예를 들어서 아래의 코드 처럼 이미 마운트 된 요소를 변경하고 싶은 경우 Ref 참조를 사용해서 변경한다.&#x20;

{% hint style="info" %}
이전에는 명령형(querySelector)으로 DOM요소에 접근했으나 이 방법은 React에서 지향하는 선언형 방법이 아니다. 그렇기 때문에 useRef() 속성을 사용해서 선언형으로 요소에 접근하는 것을 권장한다.&#x20;
{% endhint %}

```javascript
const HannaButton = ({ ...props }) => {
  return <button {...props} type="button" />;
};

export default function App() {
  const paraRef = React.useRef(null);
  React.useEffect(() => {}, []);

  // 버튼 클릭시 p 요소의 글자 색상이 변경 된다. 
  const handleClick = () => {
    paraRef.current.style.color = "rgb(167 25 25)"
  };
  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p ref={paraRef}>Start editing to see some magic happen :)</p>
      <HannaButton onClick={handleClick}>change color</HannaButton>
    </div>
  );
}
```

{% embed url="<https://stackblitz.com/edit/react-9hxzzv?file=src%2FApp.js>" %}

{% hint style="info" %}
[Ref 객체를 사용해서 리스트의 특정 요소에 접근하기 ](https://shhn0509.gitbook.io/react/react-study/mini-project/part-1/undefined)
{% endhint %}

## 3. useState vs useRef&#x20;

| 구분       | 설명                                                                                                                                                                                                |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| useState | <ul><li>이전 상태를 기억한다. </li><li>상태가 업데이트 되면 컴포넌트를 다시 렌더링한다. </li><li>즉, 이전 값을 기억하고 상태 업데이트도 필요할 때 사용한다. </li><li>예) count와 같이 상태가 계속 업데이트 되어 리렌더링이 필요할 때 사용 </li></ul>                              |
| useRef   | <ul><li>이전 상태를 기억한다. </li><li>상태가 업데이트 된다고 해도 컴포넌트를 다시 렌더링 하지 않는다. </li><li>이전 값을 기억하고 싶지만 업데이트는 필요하지 않을 때 사용한다. </li><li>예) 아코디언의 open/close와 같이 이전 상태를 기억해야 하지만 업데이트는 필요하지 않을 때 사용.  </li></ul> |
