0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

依存配列にメモ化した関数を入れるよりも、その関数をフックで定義しよう

Last updated at Posted at 2023-03-29

結論

useMemo、useEffectなどで呼び出す関数は、そのフックの中で定義します。

useCallbackでメモ化した関数をフックで使用したくない理由

公式ドキュメントに As a last resort (最後の手段)と記載されていたからです。

As a last resort, you can add a function to effect dependencies but wrap its definition into the useCallback Hook. This ensures it doesn’t change on every render unless its own dependencies also change:

理由はわかりませんが、公式がそう言っているので従うべきだと思いました。
いつかちゃんと理由を調べたいです……。

こうではなくて……

export const Component = (props) => {
    const { data } = props;
    
    const hoge = useCallback(() => {
        console.log(data);
    }, [data]};
    
    useEffect(() => {
        hoge;
    }, [hoge];
    
    // (省略)
};

こうします!

export const Component = (props) => {
    const { data } = props;
    
    useEffect(() => {
        const hoge = () => {
            // (処理省略)
        };
    
        hoge();
    }, [data]);

    // (省略)
};

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?