質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

解決済

1回答

1689閲覧

Reactのhooksに関するwarningについて

2_34_koki

総合スコア67

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

0クリップ

投稿2020/10/25 08:13

import { useRef, useEffect, useState } from "react"; type Elemntsize = { height: number; width: number; }; export const useElementSize = () => { const ref = useRef<HTMLDivElement>(null); const [size, setSize] = useState<Elemntsize>({ height: 0, width: 0 }); useEffect(() => { if (ref && ref.current) { let height = ref.current.offsetHeight; let width = ref.current.offsetWidth; setSize({ ...size, height, width }); } }, []); return { ref, size }; };

上記のようなdivのサイズを取得するhooksを書いたんですが下記のようなエラーが出ます

Line 18:6: React Hook useEffect has a missing dependency: 'size'. Either include it or remove the dependency array. You can also do a functional update 'setSize(s => ...)' if you only need 'size' in the 'setSize' call react-hooks/exhaustive-deps Search for the keywords to learn more about each warning. To ignore, add // eslint-disable-next-line to the line before.

このエラー通りにuseEffectの第2引数にsizeをセットすると無限ループしてしてしまいます.
イマイチなぜこのようなことが発生しているのかそして解決方法がわからない状態です.
知恵を貸して欲しいです.

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

import

1 2type Elemntsize = { 3 height: number; 4 width: number; 5}; 6 7export const useElementSize = () => { 8 const ref = useRef<HTMLDivElement>(null); 9 const [size, setSize] = useState<Elemntsize>({ height: 0, width: 0 }); 10 11 const getElementSize = useCallback(() => { 12 if (ref && ref.current) { 13 let height = ref.current.offsetHeight; 14 let width = ref.current.offsetWidth; 15 setSize({ height, width }); 16 } 17 }, []); 18 19 useEffect(() => getElementSize(), [getElementSize]); 20 21 return { ref, size }; 22}; 23

上記のように書き換えることで解決した

投稿2020/10/25 08:24

2_34_koki

総合スコア67

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問