1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

useMemoを使っているとReactのWarningが発生した

Posted at

状況

エディター上では何もwarningが発生しなかったのに、動作確認の段階で下記のwarningが突然発生しました
Warning: Internal React error: Expected static flag was missing. Please notify the React team.

原因

useMemoよりも手前でif returnをしていたことが原因でした

.tsx
const SampleComponent = (user) => {
  if(user=null) return

  // user を使った処理

  const [name, setName] = useState("");
  const [age, setAge] = useState(0);

  // useMemoを実行する前にreturnで返される可能性があるため、warning
  const inputData = useMemo(() => ({ name, age }), [name, age]);

  return <>...</>;
}

解決方法

  • if returnuseMemoの順序を入れ替える
    • Reactのコンポーネント内でのフックや変数の宣言の順番に関するベストプラクティスから外れてしまうので、おすすめできないです
  • userをnull非許容型の引数として宣言する
    • userがnullでなくなった時のみ、このコンポーネントを呼び出すように上位層のコンポーネントで制御すると解決できます
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?