state 값을 누적의 개념 혹은 미리 저장해놓고 활용할 수 있는 개념의 hook 함수이다

<함수형 컴포넌트 누적 이슈>

function Counter() {

    const [count, setCount] = useState(0);

    console.log("Counter 렌더링 됨...");

    const increseCount = () => {
        setCount(count + 1);
    };

    return (
        <>
            <h1>count: {count}</h1>
            <button onClick={increseCount}>카운트 증가</button>
        </>  
    );
}

해당 컴포넌트 함수는 단순하게 카운트를 버튼을 눌렀을 때 카운트가 증가되는 함수이다.

하지만, 버튼을 누를 때 마다 함수가 다시 실행되고 재 렌더링이 되므로 이전의 값을 저장하거나 누적시킬 수 없다.

case.1 지역 변수 사용

function Counter() {

    /* state 변화, 지역변수 변화, useRef값 변화 */
    const [count, setCount] = useState(0);
    let variable = 0;
 
    const increaseCount = () => {
        setCount(count + 1);
    };

    const increaseVariable = () => {
        variable += 1;
        console.log('variable:', variable);
    };

    return (
        <>
            <h1>count: {count}</h1>
            <h1>variable: {variable}</h1>
            <h1>countRef: {countRef.current}</h1>
            <button onClick={increaseCount}>카운트 증가</button>
            <button onClick={increaseVariable}>variable 증가</button>
        </>
    );
}

이렇게 variable 이라는 지역변수를 컴포넌트 함수 내부에 선언 후, 이벤트 발생 시 마다 1씩 증가 시키면 누적의 개념을 사용할 수 있을까? → 불가능하다.

console에 로그를 찍어봤을 때는 누적의 개념이 적용하지만 렌더링 시점에서는 변화X

case.2 useRef 사용

const {useState, useRef} = React;

function Counter() {
    const [count, setCount] = useState(0);

    const countRef = useRef(0);    

    const increaseCount = () => {
        setCount(count + 1);
    };

    const increaseCountRef = () => {
        // console.log(countRef.current); 현재 값
        countRef.current = countRef.current + 1;
        console.log('current:', countRef.current);
    };

    return (
        <>
            <h1>count: {count}</h1>
            <h1>countRef: {countRef.current}</h1>
            <button onClick={increaseCount}>카운트 증가</button>
            <button onClick={increaseCountRef}>카운트 ref 증가</button>
        </>
    );
}

countRef 라는 useRef가 추적하는 변수를 생성하면 리렌더링 시에도 초기화 되지 않는다.

useRef가 추적하는 변수에 변화를 줘도 화면에 변화는 일어나지 않는다.