React Hook - useRef

BANG·2025년 8월 29일

useRef

  • 랜더링과 관련 없이 동일한 참조를 유지
  • useRef의 current 값이 변경되어도 리렌더링이 발생하지 않음
  • setTimeout, setInterval 의 id, 외부 라이브러리를 사용해 생성된 인스턴스 등
  • 화면 스크롤바의 위치 등
import { useState, useRef } from 'react';
import Timer from './Component/Timer';

const App = () => {
  const [count, setCount] = useState(0);
  const countRef = useRef(0);
 
  // console.log(countRef);  // useRef는 객체를 만들어주므로 값은 .current 사용
  
  const handleCountUp = () => {
    setCount(count + 1);  // state가 변경되면 컴포넌트가 다시 랜더링됨
  }

  const handleCountRefUp = () => {
    countRef.current = countRef.current + 1;  // 값이 바뀌어도 화면이 랜더링이 되지 않음
    console.log(countRef);  // useRef는 객체를 만들어주므로 값은 .current 사용
  }

  return (
    <div>
      <p>count: {count}</p>
      <p>countRef: {countRef.current}</p>
      <button onClick={handleCountUp}>count Up</button>
      <button onClick={handleCountRefUp}>countRef Up</button>
    </div>
  )
};

export default App;
import { useState, useRef } from 'react';
import Timer from './Component/Timer';

const App = () => {
  const [renderCount, setRenderCount] = useState(0);
  let countVar = 0; // 랜더링될 때마다 초기화됨
  const countRef = useRef(0); // 랜더링되도 값을 유지함

  const handleCountVarUp = () => {
    countVar = countVar + 1;
    console.log("countVar: ", countVar);
  };

  const handleCountRefUp = () => {
    countRef.current = countRef.current + 1;
    console.log("countRef: ", countRef);
  };

  const handleRender = () => {
    setRenderCount(renderCount + 1);
  };

  return (
    <div>
      <p>countVar: {countVar}</p>
      <p>countRef: {countRef.current}</p>
      <button onClick={handleCountVarUp}>countVar Up</button>
      <button onClick={handleCountRefUp}>countRef Up</button>
      <button onClick={handleRender}>Render</button>
    </div>
  )
};

export default App;
import { useRef, useEffect } from 'react';
import Timer from './Component/Timer';

const App = () => {
  const inputRef = useRef();

  useEffect(() => {
    inputRef.current.focus(); // 자동으로 input태그에 포커스가 가게함
  }, []);

  const handleLogin = () => {
    alert(`Hi, ${inputRef.current.value}`); // ' 가 아닌 `
    inputRef.current.focus(); // 자동으로 input태그에 포커스가 가게함
  };

  return (
    <div>
      <input ref={inputRef} type='text' placeholder='username'></input>
      <button onClick={handleLogin}>login</button>
    </div>
  )
};

export default App;
profile
Record Everything!!

0개의 댓글