hyebin Lee 2022. 3. 14. 13:54

useRef

참고 유튜브 : https://www.youtube.com/watch?v=VxqZrL4FLz8

  1. useRef 변수 관리

반환된 ref는 컴포넌트가 계속해서 렌

더링이 되어도 언마운트가 되기 전까지 값을 유지 가능

변경 시 렌더링을 발생시키지 말아야 하는 값을 다룰 때 편리

실제적으로 dom 요소에 접근 가능 ex)포커스 주기 , 손쉽게 input요소 접근 가능

import

import React, { useRef, useState } from "react";
const countRef = useRef(0);
//countRef.current에 저장이 된다.

예제 코드

import React, { useRef, useState } from "react";

function Ref() {
  const countRef = useRef(0);
  const [count, setCount] = useState(0);
  let countVar = 0;
  console.log("렌더링");
  const increaseCountState = () => {
    setCount(count + 1);
  };
  const increaseCountRef = () => {
    countRef.current = countRef.current + 1;
    console.log("ref : ", countRef.current);
  };

  const increaseCountVar = () => {
    countVar = countVar + 1;
    console.log("countVar : ", countVar);
  };
  return (
    <div>
      <p>countState :{count}</p>
      <p>countRef :{countRef.current}</p>
      <p>countVar :{countVar}</p>
      <button onClick={increaseCountState}>increaseCountState</button>
      <button onClick={increaseCountRef}>increaseCountRef</button>
      <button onClick={increaseCountVar}>increaseCountVar</button>
    </div>
  );
}

export default Ref;

ref는 버튼을 눌러도 바로 화면에 보이지 않는다.

이유는 컴포넌트를 렌더링 시키지 않기 때문에 화면에 업데이트가 되지 않아 보이지 않는다.

이때 state를 +1 해주면 화면에 나타나게된다.

컴포넌트가 렌더링이 될 때 함수가 불리게 되므로 함수 countVar은 초기화가 된다.

ref는 렌더링이 되어도 값을 유지한다. 마운팅 된 부터 마운팅 해제될 때 까지 같은 값 유지

import React, { useEffect, useRef, useState } from "react";

function Ref() {
  const [count, setCount] = useState(1);
  const [returnCount, setReturnCount] = useState(1);

  //   useEffect(() => {
  //     console.log("렌더링");
  //     setReturnCount(returnCount + 1);
  //   });

  return (
    <div>
      <p>count:{count}</p>
      <button onClick={() => setCount(count + 1)}></button>
    </div>
  );
}

export default Ref;

 useEffect(() => {
   console.log("렌더링");
   setReturnCount(returnCount + 1);
 });

코드를 실행하면 위와같은 에러가 발생한다. 이유는 버튼을 누르면 countState가 업데이트 되기 때문에 useEffect가 불린다. 그런데 useEffect 안에도 setReturnCount가 업데이트 시키는 코드가 있다. 이는 무한이 반복되게 된다. 이때 ref를 사용한다.

import React, { useEffect, useRef, useState } from "react";

function Ref() {
  const [count, setCount] = useState(1);
  const renderCount = useRef(1);

  useEffect(() => {
    renderCount.current = renderCount.current + 1;
    console.log("렌더링 수 ", renderCount.current);
  });

  return (
    <div>
      <p>count:{count}</p>
      <button onClick={() => setCount(count + 1)}>돌려</button>
    </div>
  );
}

export default Ref;

ref는 리렌더링을 발생시키지 않아 무한루프에 빠트리지 않는다!

 

   2.  useRef Dom요소 접근

const ref = useRef(value)는 ref오브젝트를 반환한다. 이 오브젝트를 접근하고자 하는 요소 ref={ref} 로 넣으면 쉽게 접근이 가능하다. 예를 들어 로그인 페이지가 로그인되어 화면에 보여줬을 때 클릭하지 않아도 바로 포커스 되게 해줄 수 있다.

 

dom요소에 접근 하여 포커스를 자동으로 시켜주는 코드

import React, { useEffect, useRef, useState } from "react";

function Ref() {
  const inputRef = useRef();

  useEffect(() => {
    console.log(inputRef);
    inputRef.current.focus();
  }, []);

  const login = () => {
    alert(`환영합니다. ${inputRef.current.value}`);
    inputRef.current.focus();
  };
  return (
    <div>
      <input ref={inputRef} type="text" placeholder="username" />
      <button onClick={login}>로그인</button>
    </div>
  );
}

export default Ref;