React/기초

[React] Hooks - forwardRef

고기고기물고기 2022. 12. 28. 16:18

React에서 기본적으로 지원하는 Hooks

1. useState

컴포넌트의 state(상태)를 관리 할 수 있다.

상태에 따라, 다른 화면 출력

2. useEffect

렌더링 이후에 실행할 코드를 만들수 있다.

어떤 변수가 변경될때마다(의존성), 특정기능이 작동하도록 할 수 있다.

3. useContext

부모컴포넌트와 자식컴포넌트 간의 변수와 함수를 전역적으로 정의할 수 있다.

4.  useReducer

state(상태) 업데이트 로직을, reducer 함수에 따로 분리 할 수 있다.

5. useRef

컴포넌트나 HTML 요소를 래퍼런스로 관리할 수 있다.

6. forwardRef

useRef로 만든 래퍼런스를 상위 컴포넌트로 전달할 수 있다.

7. useImperativeHandle

useRef로 만든 래퍼런스의 상태에 따라, 실행할 함수를 정의 할 수 있다.

8. useMemo, useCallback

의존성 배열에 적힌 값이 변할 때만 값,함수를 다시 정의할 수 있다. ( 재랜더링시 정의 안함 )

8. useLayoutEffect

모든 DOM 변경 후 브라우저가 화면을 그리기(render)전에 실행되는 기능을 정할 수 있다.

9. useDebugValue

사용자 정의 Hook의 디버깅을 도와준다.

forwardRef 예제

 

App.js

 

import React, { useRef } from "react";
import Cat from "./components/Cat";
import "./styles.css";

export default function App() {
  const catRef = useRef();

  return (
    <div>
      <h4> 고양이가 세상을 구한다 ️</h4>
      <div>
        <Cat ref={catRef} />
      </div>
    </div>
  );
}

 

Cat.js  -- const 예제

import React, { forwardRef } from "react";

const Cat = forwardRef((props, ref) => {
  console.log(ref);

  return (
    <div>
      <img
        src="https://static01.nyt.com/images/2016/03/30/universal/ko/well_cat-korean/well_cat-superJumbo-v2.jpg?quality=90&auto=webp"
        alt="cat"
        style={{ width: "150px" }}
        ref={ref}
      ></img>
    </div>
  );
});

export default Cat;

 

결과 : https://codesandbox.io/s/charming-platform-77dnl?from-embed=&file=/src/components/Cat.js 

 

charming-platform-77dnl - CodeSandbox

charming-platform-77dnl by leehwarang using react, react-dom, react-scripts

codesandbox.io

 

function 예제

 

// Audio.jsx
import React, { forwardRef } from "react";
import music from "./music.mp3";

function Audio(prop, ref) {
  return (
    <figure>
      <figcaption>Eyes on You (Sting) - Network 415:</figcaption>
      <audio src={music} ref={ref}>
        Your browser does not support the
        <code>audio</code> element.
      </audio>
    </figure>
  );
}

export default forwardRef(Audio);