728x90
728x90

state와 ref 비교하기

들어가며

  • 리액트에서 자주 사용되는 refstate를 비교해보자.

 

비교

  • useState를 통해 생성된 객체는 리렌더링 중에 초기화가 되지만, useRef를 통해 생성된 객체는 리렌더링 중에 초기화가 되지 않는다.
  • useState[value, setValue]를 반환하고, useRef{ current : value }를 반환한다.

 

ref state
useRef(initialValue){ current: initialValue }을 반환 useState(initialValue)state 변수의 현재값과 state 설정자 함수([value, setValue])를 반환
Mutable
→ 렌더링 프로세스 외부에서 current 값을 수정하고 업데이트할 수 있음.
 Immutable
state 설정자 함수를 사용하여 state 변수를 수정해 리렌더링을 대기열에 추가해야 함.
변경 시 리렌더링을 촉발하지 않음.  변경 시 리렌더링을 촉발함.
렌더링 중에는 current 값을 읽거나 쓰지 않아야 함.  언제든지 state를 읽을 수 있음.
각 렌더링에는 변경되지 않는 자체 state Snapshot이 있음.

 

사용 예제 코드

useState 

import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
export default Counter;

 

useRef 

import React, { useRef } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<div>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</div>
);
}
export default TextInputWithFocusButton;

 

참고 사이트

 

ref로 값 참조하기 – React

The library for web and native user interfaces

react-ko.dev

 

728x90
728x90

state와 ref 비교하기들어가며비교사용 예제 코드useState useRef 참고 사이트