😀

親コンポーネントのrefを参照する

2023/03/31に公開

はじめに

親コンポーネントのrefを子コンポーネントから参照する方法を説明します。

説明

下のコードはParentコンポーネントのボタンをクリックした回数をChildコンポーネントのボタンをクリックしたときにalertで表示するコードです。

一つポイントがあって、childコンポーネントのpropsとしてcountRef.currentではなく、countRefをそのまま渡すことです。

countRef.currentを渡しても正しく動くのですが、parentコンポーネントのボタンをクリックするたびにpropsが変更されるので、Childコンポーネントがサイレンダリングされてしまいます。

countRefを渡せば、countRef.currentが変更されてもpropsの変更は検知されないのでサイレンダリングは発生しません。(「ref.currentが変更されても再レンダリングされない」という挙動を維持出来ています。)

親コンポーネントののRefをpropsとして渡す時には注意しましょう。

import { MutableRefObject, useRef } from "react";

export const Parent = () => {
  const countRef = useRef<number>(0);
  const handleClick = () => {
    countRef.current = countRef.current + 1;
  };
  return (
    <>
      <button onClick={handleClick}>parent button</button>
      <Child countRef={countRef} />
    </>
  );
};

type Props = {
  countRef: MutableRefObject<number>;
};
const Child = (props: Props) => {
  const { countRef } = props;
  const handleClick = () => {
    alert("parent button is clicked " + countRef.current + "times");
  };
  return <button onClick={handleClick}>child button</button>;
};

Discussion