✏️Example
랜더링 된다는 것은 컴포넌트가 다시 불린다는 것이다.
import React, { useState } from "react";
export default function useRefs() {
const [count, setCount] = useState(0);
console.log("랜더링");
const increaseCountState = () => {
setCount(count + 1);
};
return (
<div>
<p>State : {count}</p>
<button onClick={increaseCountState}>State Up</button>
</div>
);
}
button이 눌릴때마다, 재랜더링이 되면서 function useRefs()가 새로 불리고,
안에 있는 코드들이 새로 불려오는 작업이 실행된다.
✏️ Ref Example -1
import React, { useState, useRef } from "react";
export default function useRefs() {
const [count, setCount] = useState(0);
const countRef = useRef(0);
console.log(countRef);
console.log("랜더링");
const increaseCountState = () => {
setCount(count + 1);
};
return (
<div>
<p>State : {count}</p>
<button onClick={increaseCountState}>State Up</button>
</div>
);
}
useRef 는 하나의 object이다.
console로 출력하면 object로 출력이 되고, useRef로 설정해준 초기값을 갖는다.

✏️ Ref Example -2
import React, { useState, useRef } from "react";
export default function useRefs() {
const [count, setCount] = useState(0);
const countRef = useRef(0);
console.log(countRef);
console.log("랜더링");
const increaseCountState = () => {
setCount(count + 1);
};
const increaseCountRef = () => {
countRef.current = countRef.current + 1;
console.log(countRef.current);
};
return (
<div>
<p>State : {count}</p>
<p>Ref : {countRef.current}</p>
<button onClick={increaseCountState}>State Up</button>
<button onClick={increaseCountRef}>Ref Up</button>
</div>
);
}
ref 버튼을 아무리 입력해도 Ref<p> 값은 변하지 안고,
state 버튼을 누르는 순간, 업데이트 된다.
이것은 ref 값이 아무리 바뀌어도 랜더링 되지 않는다는 것을 의미한다.
📌 수시로 바뀌는 값은 state에 담으면 랜더링이 빈번하게 일어나기 때문에, 성능에 좋지 않다.
따라서 자주 바뀌는 값은 state보다는 ref에 보관하는 것이 효율적이다.