LoginSignup
14

More than 3 years have passed since last update.

【React】Warning: Cannot update a component from inside the function body of a different component.

Last updated at Posted at 2020-03-18

Reactのバージョンを16.12.0 → 16.13.0にした時に下の様なWarningが出て困った。

Warning: Cannot update a component from inside the function body of a different component.

なんだこのWarning!?

日本語の情報が少ない中、reactのissuesやstackoverflowを一生懸命探してみたが、最終的に公式のBlogにたどり着いた。
https://reactjs.org/blog/2020/02/26/react-v16.13.0.html

It is supported to call setState during render, but only for the same component. If you call setState during a render on a different component, you will now see a warning:

レンダリング中にsetStateを呼び出すことはサポートされていますが、同じコンポーネントに対してのみです。別のコンポーネントでのレンダリング中にsetStateを呼び出すと、警告が表示されます。

ということらしい。

これだとWarningが出る。
Hogeのレンダリング中にFugaでsetStateを呼び出しているのが原因っぽい。

App.tsx
import React, { useState } from "react";
interface Props {
  setCount: Function;
}
const Fuga: React.FC<Props> = ({ setCount }) => {
  setCount(1);
  return <p>test</p>;
};
const Hoge: React.FC = () => {
  const [count, setCount] = useState(0);
  return <Fuga setCount={setCount} />;
};
export default Hoge;

これを解決する方法は、もちろん公式に書いてある。

In the rare case that you intentionally want to change the state of another component as a result of rendering, you can wrap the setState call into useEffect.

レンダリングの結果として意図的に別のコンポーネントの状態を変更したいというまれなケースでは、setState呼び出しをuseEffectにラップできます。

要するに、setStateをuseEffectでラップすれば良いらしい。
これだと、Warningは出ない。

App.tsx
import React, { useState, useEffect } from "react";
interface Props {
  setCount: Function;
}
const Fuga: React.FC<Props> = ({ setCount }) => {
  useEffect(() => {
    setCount(1);
  }, [setCount]);
  return <p>test</p>;
};
const Hoge: React.FC = () => {
  const [count, setCount] = useState(0);
  return <Fuga setCount={setCount} />;
};
export default Hoge;

無事解決!
ふぅ、焦ったー。。。

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
14