어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ

🟦 [React] useRef 개념 잡기 본문

개발/🟦 React

🟦 [React] useRef 개념 잡기

비니_ 2025. 3. 9. 09:52
728x90

❓ useRef는 React에서 DOM 요소나 값을 저장할 때 사용하는 훅

=> id 역할

 

✔️ 컴포넌트가 리렌더링되어도 값이 유지됨

 

✔️ 값이 바뀌어도 리렌더링되지 않음!! => useState와 다른점❗

=> current로 console.log를 찍어보면 값은 증가하고 있지만 리렌더링을 하지 않는 이상 화면에는 변화가 없음

 

 

const fileInputRef = useRef(null);

<input type="file" ref={fileInputRef} />

👩🏻질문사항👩🏻

id 값은 useRef로 받아온다, JS처럼 getElementById로 가져와도 되지만 리액트를 사용하기 때문에 리액트 기능 사용
이유: 리렌더링이 되지 않고 input에 연결된 파일 값을 가지고 있기 때문

=> 가지고 있다가 내가 뿌려줘야 그 값을 뿌려준다
useRef => 해당 값을 가지고 있는다 / form에서 submit 같은거 할 때 많이 사용

 

 

📌 useState vs useRef 차이

  useState useRef
값 변경 시 리렌더링 발생 리렌더링 없음
초기값 저장 O O
DOM 접근 X O
import React, { useRef, useState } from "react";

const Counter = () => {
  const countRef = useRef(0); // 상태 저장 (리렌더링되지 않음)
  const [renderCount, setRenderCount] = useState(0); // 리렌더링 확인용

  const increaseRef = () => {
    countRef.current += 1; // 값 증가 (하지만 리렌더링 안 됨)
    console.log("useRef 값:", countRef.current);
  };

  return (
    <div>
      <p>렌더링 횟수: {renderCount}</p>
      <button onClick={increaseRef}>useRef 증가</button>
      <button onClick={() => setRenderCount(renderCount + 1)}>리렌더링</button>
    </div>
  );
};

export default Counter;

 

 

✔️ DOM 요소를 직접 접근할 때 사용

=> ex) 버튼을 누르면 input에 자동 포커스가게 하기

import React, { useRef } from "react";

const InputFocus = () => {
  const inputRef = useRef(null); // input 요소를 저장할 ref 생성

  const handleClick = () => {
    inputRef.current.focus(); // input에 포커스 설정
  };

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="여기에 입력하세요" />
      <button onClick={handleClick}>포커스 이동</button>
    </div>
  );
};

export default InputFocus;

 

 

 

 

728x90
Comments