[React] useState vs useRef

에구마·2022년 3월 27일
0

FrontEnd

목록 보기
4/25

useRef의 용도
1. 변수(state)관리
2. DOM 선택

state 변경시 렌더링 차이

useState와 useRef 모두 state를 변경시킬 수 있다

useState

state 변경되면 재렌더링 발생

useRef

state 변경 후 재렌더링 하지 않음!!
값을 바꿔도 바뀐 값이 화면에 보이지 않음
콘솔에선 확인 할 수 있음

function App() {
  const [stateValue, setStateValue] = useState(0);
  const refValue = useRef(null);
  console.log(`랜더링... count: ${stateValue}`);

  return (
    <>
      <p>{stateValue}번 클릭하셨습니다.</p>
      <p>{refValue.current  } ref.</p> 
      
      <button onClick={() => {setStateValue(stateValue+1);
        console.log(stateValue);
      }}>setStateValue</button>
      <button onClick={() => {
        refValue.current+=1;
        console.log(refValue);
        }}>setStateValue</button>
    </>
  );
}


useRef

특정 DOM 선택

JS에서 getElementById, querySelector 등 selector함수 사용하듯.
리액트에선 ref를 사용한다! useRef란 훅스함수를 사용하면서!

  const nameInput = useRef();
  ...
  return(
      <input placeholder="이름" value={name}
        ref={nameInput}
      />
  	)

onChange 등 이벤트 함수에서

nameInput.current.focus();

하면 ref 설정한 input 태그에 focus를 줄 수 있음.

profile
Life begins at the end of your comfort zone

0개의 댓글