SW Engineer & Developer/React Craft

React의 ref

ByteCraft 2025. 2. 3. 21:07

 

개요
import { useEffect, useRef } from "react";

function FileInput({ name, value, onChange }) {
  const inputRef = useRef();

  const handleChange = (e) => {
    const nextValue = e.target.files[0];
    onChange(name, nextValue);
  };

  return <input ref={inputRef} type='file' onChange={handleChange} />;
}

export default FileInput;

useRef()가 뭔가?

 

React의 ref

React의 ref는 DOM 요소나 클래스 컴포넌트 인스턴스에 직접 접근할 수 있도록 도와주는 기능입니다.

 

🔹 ref의 주요 개념

  1. DOM 요소 접근: ref를 사용하면 document.querySelector 없이도 특정 DOM 요소를 직접 조작할 수 있습니다.
  2. 컴포넌트 인스턴스 접근: 클래스 컴포넌트의 메서드나 속성에 접근할 수 있습니다.
  3. 값 유지: ref는 컴포넌트가 리렌더링되어도 값이 유지됩니다.

🔹 ref 사용법

 

1.useRef를 활용한 DOM 접근 (함수형 컴포넌트)

import { useRef, useEffect } from "react";

function InputFocus() {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus(); // 컴포넌트가 마운트되면 자동으로 포커스
  }, []);

  return <input ref={inputRef} placeholder="자동 포커스" />;
}

 

2.createRef를 활용한 클래스 컴포넌트의 ref

import React, { Component, createRef } from "react";

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.inputRef = createRef();
  }

  focusInput = () => {
    this.inputRef.current.focus();
  };

  render() {
    return (
      <>
        <input ref={this.inputRef} />
        <button onClick={this.focusInput}>포커스</button>
      </>
    );
  }
}

 

3.useRef를 활용한 상태 유지

import { useRef, useState } from "react";

function Counter() {
  const countRef = useRef(0);
  const [state, setState] = useState(0);

  const increaseRef = () => countRef.current++;
  const increaseState = () => setState(state + 1);

  return (
    <>
      <p>Ref 값: {countRef.current}</p>
      <p>State 값: {state}</p>
      <button onClick={increaseRef}>Ref 증가</button>
      <button onClick={increaseState}>State 증가</button>
    </>
  );
}

🚀 countRef.current는 상태 변경 없이 값만 증가하므로 리렌더링되지 않음!

 

결론 및 요약

 

  • ref 값이 변경되어도 컴포넌트는 리렌더링되지 않음
  • 가능하면 state를 먼저 고려하고, 필요할 때만 ref를 사용
  • ref를 직접 수정하는 것은 React의 선언형 패턴과 다를 수 있으므로 신중히 사용