Use Imperative Handle

Hyphen, underscore, or camelCase as word delimiter in URIs?

useImperativeHandle

forwardRef와 함께 사용하여

부모에 노출시킬 함수를 정하는 기능

import React, { useRef, useImperativeHandle, forwardRef } from 'react';

// 자식 컴포넌트
const FocusInput = forwardRef((props, ref) => {
  const inputRef = useRef();

  // useImperativeHandle을 사용하여 부모에게 노출할 함수를 지정
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    },
    blur: () => {
      inputRef.current.blur();
    }
  }));

  return <input ref={inputRef} />;
});

// 부모 컴포넌트
const ParentComponent = () => {
  const childRef = useRef();

  const handleFocus = () => {
    // 자식 컴포넌트의 포커스 함수 호출
    childRef.current.focus();
  };

  const handleBlur = () => {
    // 자식 컴포넌트의 블러 함수 호출
    childRef.current.blur();
  };

  return (
    <div>
      <button onClick={handleFocus}>Focus Input</button>
      <button onClick={handleBlur}>Blur Input</button>
      <FocusInput ref={childRef} />
    </div>
  );
};

export default ParentComponent;

언제 사용할까요?

  1. 부모-자식 간 통신이 필요한 경우:
  2. 라이브러리나 외부 모듈에서 사용하는 경우:

주의해야 할 점:

  1. 컴포넌트 설계 재고:
  2. React의 철학과 맞지 않는 경우:
  3. 의존성 배열 주의:

Unlighthouse

Unlighthouse is a tool to scan your entire site with Google Lighthouse in 2 minutes (on average). Open source, fully configurable with minimal setup.