React - useRef()

gyu0714·2022년 11월 4일
1

Hooks

목록 보기
3/9
post-thumbnail

useRef

useRef Hook을 사용하면 렌더 간에 값을 유지할 수 있다.
업데이트할 때 다시 렌더링하지 않는 변경 가능한 값을 저장하는데 사용할 수 있다.
DOM 요소에 직접 액세스하는 데 사용할 수 있다.

다시 렌더링하지 않음

Hook을 사용하여 애플리케이션이 몇 번 렌더링 되는지 계산하려고 하면 useState Hook 자체가 다시 렌더링을 일으키기 때문에 무한루프에 빠지게 된다.
이를 피하기 위해 useRef Hook을 사용할 수 있다.

import { useState, useEffect, useRef } from 'react'

function App() {
	const [inputValue, setInputValue] = useState("");
    const count = useRef(0);
    
    useEffect(() => {
    	count.current = count.current + 1; 
    })
    
    return (
    	<>
        	<input
            	type = "text"
                value = {inputValue}
                onChange = {(e) => setInputValue(e.target.value)}
             />
             <h1>{count.current}</h1>
        </>
    )
}

초기화 useRef할 때 초기 값을 설정한다. useRef(0)

DOM 요소 접근

일반적으로 React가 모든 DOM 조작을 처리하도록 하고 싶지만 useRef 문제를 일으키지 않고 사용할 수 있는 경우가 있다. React에서는 ref요소 속성을 추가하여 DOM에서 직접 접근할 수 있다.

import { useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const inputElement = useRef();

  const focusInput = () => {
    inputElement.current.focus();
  };

  return (
    <>
      <input type="text" ref={inputElement} />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

상태 변경 추적

Hook은 useRef 이전 상태 값을 추적하는 데에도 사용할 수 있다.
useRef는 렌더링 간에 값을 유지할 수 있기 때문이다.

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const [inputValue, setInputValue] = useState("");
  const previousInputValue = useRef("");

  useEffect(() => {
    previousInputValue.current = inputValue;
  }, [inputValue]);

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h2>Current Value: {inputValue}</h2>
      <h2>Previous Value: {previousInputValue.current}</h2>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

useState, useEffect, 및 조합을 사용하여 useRef의 이전 상태를 추적 할 수 있다.
예제에서 입력 필드에 텍스트를 입력하여 업데이트 될 때마다 현재 값 useEffect을 업데이트하고 있다.

정리

  • useRef는 DOM에 직접적으로 접근한다.
  • React로 ref 객체를 전달한다면, React는 노드가 변경될 때마다 변경된 DOM 노드에 current 프로퍼티를 설정 할 것이다.
  • useRef()는 어떤 가변값을 유지하는 데에 편리하다.
  • useRef()는 순수 자바스크립트 객체를 생성하기 때문에 useRef()와 {current: ...} 객체 자체를 생성하는 것의 유일한 차이점이라면 useRef는 매번 렌더링을 할 때 동일한 ref 객체를 제공한다는 것이다.
profile
gyu0714

0개의 댓글