LoginSignup
4
5

More than 3 years have passed since last update.

Reactでwindowに対して、resizeイベントを登録していた時のエラー

Last updated at Posted at 2017-10-09

よくわからないエラーが発生

ReactでSemanticUIを使い始め、windowにたいして、Resizeイベントを登録していたある日のこと。

componentDidMount() {
    window.addEventListener('resize', () => {
        setState({smallScreen: window.innerWidth < 600});
    });
}

上記のコードで、動かした際に、画面をリサイズするたびに、下記のエラーが発生していた。

Warning: setState(...): Can only update a mounted or mounting component. 
This usually means you called setState() on an unmounted component.
This is a no-op. Please check the code for the ****** component.

それまでこんなエラー出てなかったもので、突然のことに困惑しつつ、所詮Warningであるからと甘えていたが、下記のようにcomponentWillUnmountイベントにてremoveEventListenerすることでで解決した。

componentWillUnmount() {
    window.removeEventListener('resize', registeredListener);
}

原因は、コンポーネントがアンマウント後も、コールバックが呼ばれていたためですね。

現在だと、React hooksつかって

const [screenIsSmall, setScreenIsSmall] = useState(false);

useEffect(() => {
    window.addEventListener('resize', () => {
        setScreenIsSmall(window.innerWidth < 600);
    });

    return () => window.removeEventListener('resize', registeredListener);
})

とすれば良いですね。

以上、現場からでした。

4
5
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
4
5