기록

useRef와 forwardRef

als982001 2023. 8. 13. 16:58

1. useRef

1-1. useRef란

  • React Hooks 중 하나
  • DOM 요소에 접근하거나 렌더 사이에 값을 유지하기 위해 사용
  • current라는 프로퍼티를 가진 mutable한(값이 변경될 수 있는) 객체를 반환
  • 사용 예시
const inputRef = useRef(null);

 

1-2. useRef는 언제 이용하는가

  • DOM 접근
    • React는 DOM 요소를 직접 건드리는 것을 지양하지만, 가끔씩 DOM 요소를 조작해야 할 때가 있다. 이럴 경우 useRef를 이용할 수 있다. 아래의 예시는 Img를 클릭할 경우, 숨겨진 input을 useRef를 활용해 클릭하는 코드이다.
import { useRef } from "react";

export default function useRegist() {
  const imageInputRef = useRef<HTMLInputElement>(null);
 
  const handleInputClick = () => {
    if (imageInputRef.current) {
      imageInputRef.current.click();
    }
  };

  return {
    imageInputRef,
    handleInputClick,
  };
}

// 생략

export default function Regist() {
  const {
    imageInputRef,
    handleInputClick,
  } = useRegist();

  useEffect(() => {
    checkLogin();
  }, []);

  return (
    <div>
        <Img bgImage={imageUrl} onClick={handleInputClick}>
            {imageUrl.length === 0 && "클릭하여 이미지를 등록해주세요."}
        </Img>
        <input
            type="file"
            accept="image/*"
            onChange={handleImagePost}
            style={{ display: "none" }}
            ref={imageInputRef}
        />
    </div>
  );
}

 

  • 렌더 사이의 값을 유지
    • useState는 상태가 변경될 때마다 리렌더링하지만 useRef는 그렇지 않다. 이를 통해 값의 변경에 따른 리렌더링 없이 값을 유지하고 싶을 때 이용할 수 있다.
const renderCount = useRef(0);

useEffect(() => {
  renderCount.current += 1;
});

return <div>{`Count: ${renderCount.current}`} </div>;

 

 

2. forwardRef

2-1. forwardRef란

  • React의 유틸리티 중 하나.
  • 일반적으로 React 컴포넌트는 ref prop를 받지 못함. 하지만 가끔씩 ref를 전달해야 할 때가 있음. 이 때, forwardRef컴포넌트 사이 ref를 전달(forward)하거나 전달받을 수 있게 해줌.

 

2-2. forwardRef는 언제 이용하는가?

  • 컴포넌트 내부의 DOM 요소에 접근하고 싶을 때
    • 컴포넌트를 추상화하여 재사용하면서, 컴포넌트 내부의 특정 DOM 요소에 접근하고 싶을 때가 있을 수 있다. 이럴 때 forwardRef를 이용할 수 있다. 아래는 이에 대한 예시 코드로 chatGPT의 도움을 받았다. 
const CustomInput = React.forwardRef((props, ref) => {
  return <input {...props} ref={ref} />;
});

function App() {
  const inputRef = useRef(null);

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <CustomInput ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

 

  • 하위 컴포넌트 전체에 ref를 연결하고 싶을 때
    • 간혹 특정 컴포넌트 전체를 대상으로 DOM API나 인스턴스 메서드를 사용해야 할 때가 있다. 이 때 forwardRef를 통해 부모 컴포넌트에서 해당 컴포넌트 인스턴스에 직접 접근할 수 있다.

 

2-3. forwardRef 예시

// 관련이 없는 부분은 생략함
export default function List() {
  const { places, isLoading, addIndex } = useGetPlaces();
  const bottomRef = useRef(null);
    
  return (
    <Wrapper>      
      <ToTopButton onClick={() => window.scrollTo(0, 0)} ref={bottomRef} />
    </Wrapper>
  );
}

 위 코드의 List에는 ToTopButton이 있다. 이 버튼은 두 가지 역할을 한다. 첫 번째는 클릭할 경우 가장 위로 이동하게 하는 것(window.scrollTo(0, 0))이다. 두 번째는 무한스크롤을 위해 이 버튼이 화면에 노출될 경우, 데이터를 더 받아오게 하는 것이다. 이 버튼이 화면에 노출되었는지를 확인하기 위해서 이 ref를 이용해야 한다. 이제 ToTopButton을 확인해보자.

 

 

import styled from "styled-components";

interface IProps {
  onClick: () => void;
  ref: React.MutableRefObject<null>
}

export default function ToTopButton(props: IProps) {
  return (
    <Button onClick={props.onClick} ref={props.ref}>
      <TextOne className="text-one">
        <AiOutlineArrowUp size={"30px"} />
      </TextOne>
      <TextTwo className="text-two">
        <BsFillRocketFill size={"30px"} />
      </TextTwo>
    </Button>
  );
}

ToTopButton은 onClick과 ref를 props로 받는다. 그렇기에 위처럼 onClick과 ref를 적용해주면 될 것이다. 하지만 에러가 발생했다.(에러 화면은 캡쳐하지 못했다.) 그렇기에 ToTopButton에 forwardRef를 적용할 것이다.

 

 

import styled from "styled-components";
import React from "react";

interface IProps {
  onClick: () => void;
}

const ToTopButton = React.forwardRef<HTMLButtonElement, Omit<IProps, "ref">>(
  (props, ref) => {
    return (
      <Button onClick={props.onClick} ref={ref}>
        <TextOne className="text-one">
          <AiOutlineArrowUp size={"30px"} />
        </TextOne>
        <TextTwo className="text-two">
          <BsFillRocketFill size={"30px"} />
        </TextTwo>
      </Button>
    );
  }
);

ToTopButton.displayName = "ToTopButton";

export default ToTopButton;

ToTopButton에 forwardRef를 적용하여 ref를 무사히 이용할 수 있었다.

 

 forwardRef를 이용하기 위해서는 기본적으로 두 가지 매개변수 (props, ref)를 입력 받는다.

const TestInput = React.forwardRef((props, ref) => {
  return <input ref={ref} {...props} />;
});

props는 ref를 제외하고 전달해주고 싶은 props이고 ref는 방금 이야기했던 ref이다. 그리고 타입스크립트에서는 타입을 지정해줘야 한다. 예를 들어, 위의 ToTopButton을 다시 보자.

 

 

interface IProps {
  onClick: () => void;
}

const ToTopButton = React.forwardRef<HTMLButtonElement, Omit<IProps, "ref">>(
  (props, ref) => {
    return (
      <Button onClick={props.onClick} ref={ref}>
		// 생략
      </Button>
    );
  }
);
  • forwardRef두 개의 제네릭 타입 인수를 받을 수 있다. 우선, Button은 const Button = styled.button``이다. 그렇기에 DOM 요소의 타입으로 HTMLButtonElement를 제네릭 타입으로 지정하였다.
  • Omit<IProps, "ref">에서 Omit은 주어진 타입(여기서는 IProps)에서 특정 키(여기서는 "ref")를 제거하여 새로운 타입을 만들 수 있다. 그렇기에 IProps에서 "ref"를 제거한 제네릭 타입을 지정하였다. IProps에는 ref 프로퍼티가 있지만 forwardRef를 사용할 때는 ref를 직접적으로 전달하지 않는다. 그렇기에 이 프로퍼티를 제거하였다. 그 결과, ToTopButton 컴포넌트는 ref를 제외한 나머지 props만을 받게 된다.