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
をセットすると無限ループしてしてしまいます.
イマイチなぜこのようなことが発生しているのかそして解決方法がわからない状態です.
知恵を貸して欲しいです.
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。