iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌊

State Not Updating in useEffect with an Empty Dependency Array

に公開
2023/08/05
4件

Overview

As the title suggests, I recently forgot the behavior of useEffect and got stuck, so I'm documenting the solution here.

What is the situation where state is not updated?

There are times when you want to run some processing when a component mounts by leaving the second argument's dependency array of useEffect empty. This post is about how state is not updated even if you reference it in such cases.

Basically, since the standard advice is to "pass the state into the dependency array," the case above doesn't happen very often. However, it becomes an issue when using things like setInterval or addEventListener during mounting.

In my case, it was a bit specific, as I encountered this problem while implementing WebSocket. I'll use that as an example this time. If you don't know what WebSocket is, it's enough to understand that it performs asynchronous communication.

Reference URL: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

Code where state is not updated

First, here is the overall code.

import React, { useEffect, useState, useRef } from "react";

const Index = () => {
  const [fruit, setFruit] = useState("orange");
  const ws = useRef();

  const selectFruit = e => {
    // Sending data
    // In this case, we are sending data to "wss://echo.websocket.org". If the transmission is successful, the sent content is returned as is.
    // As a result, the "message" event is fired.
    ws.current.send(e.currentTarget.getAttribute("data-fruit"));
  };

  useEffect(() => {
    // When data is sent to this URL via WebSocket, the sent data is returned as is.
    const url = "wss://echo.websocket.org";

    // Create WebSocket connection
    ws.current = new WebSocket(url);

    // When the connection is established
    ws.current.addEventListener("open", e => {
      console.log("Connection started");
    });

    // When a message is received
    // In this case, the data sent by the selectFruit function is returned as is.
    ws.current.addEventListener("message", e => {
      // Show an alert if fruit is already the selected value
      if (fruit === e.data) {
        alert("Select different fruit.");
      }
      setFruit(e.data);
    });

    // When an error occurs
    ws.current.addEventListener("error", e => {
      console.log("Error: " + e.data);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div>
      <p>fruit: {fruit}</p>
      <div>
        <button onClick={selectFruit} data-fruit="orange">
          orange
        </button>
        <button onClick={selectFruit} data-fruit="apple">
          apple
        </button>
        <button onClick={selectFruit} data-fruit="banana">
          banana
        </button>
      </div>
    </div>
  );
};

export default Index;

With the above code, the state referenced in the WebSocket message event is not updated, so the part that says "Show an alert if fruit is already the selected value" does not behave as intended.

Why is the state not updated?

Take a look at the following part:

ws.current.addEventListener("message", e => {
  // Show an alert if fruit is already the selected value
  if (fruit === e.data) {
    alert("Select different fruit.");
  }
  setFruit(e.data);
});

Ideally, this code is intended to compare the fruit state with the newly selected button, and:

  • Show an alert if the value is the same
  • Only fire the setFruit function if the value is different

However, with this setup, fruit inside the message event will always be "orange". Since setFruit itself is working, the fruit within the return statement (the part below) does get updated.

<p>fruit: {fruit}</p>

For those seeing this for the first time, it might seem like a strange behavior, but if you're familiar with closures, you can likely understand it.

const [fruit, setFruit] = useState("orange");

// Executed only on mount
useEffect(() => {
  ws.current.addEventListener("message", e => {
    // Captures fruit (orange) from the initial render
    if (fruit === e.data) {
      alert("Select different fruit.");
    }
    setFruit(e.data);
  });
}, []);

When useEffect is called, the addEventListener callback captures fruit. Since the second argument of useEffect is empty this time, useEffect only runs at mount. This means the value of fruit is never updated after the initial mount.

As a result, fruit inside addEventListener will always refer to the initial value ("orange").

Solution

So, what should we do? First, here is the fixed code.

import React, { useEffect, useState, useRef } from "react";

const Index = () => {
  const [fruit, setFruit] = useState("orange");
  const ws = useRef();
  const refFruit = useRef(fruit);

  const selectFruit = e => {
    ws.current.send(e.currentTarget.getAttribute("data-fruit"));
  };

  useEffect(() => {
    const url = "wss://echo.websocket.org";
    ws.current = new WebSocket(url);

    ws.current.addEventListener("open", e => {
      console.log("Connection started");
    });

    ws.current.addEventListener("message", e => {
      if (refFruit.current === e.data) {
        alert("Select different fruit.");
      }
      setFruit(e.data);
    });

    ws.current.addEventListener("error", e => {
      console.log("Error: " + e.data);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    refFruit.current = fruit;
  }, [fruit]);

  return (
    <div>
      <p>fruit: {fruit}</p>
      <div>
        <button onClick={selectFruit} data-fruit="orange">
          orange
        </button>
        <button onClick={selectFruit} data-fruit="apple">
          apple
        </button>
        <button onClick={selectFruit} data-fruit="banana">
          banana
        </button>
      </div>
    </div>
  );
};

export default Index;

The following three parts are important:

// Define newly with useRef
const refFruit = useRef(fruit);

// Compare using the variable defined with useRef
ws.current.addEventListener("message", e => {
  if (refFruit.current === e.data) {
    alert("Select different fruit.");
  }
  setFruit(e.data);
});

// Add fruit to the dependency array and update refFruit
useEffect(() => {
  refFruit.current = fruit;
}, [fruit]);

While I'm not entirely sure about the exact internal mechanism, it seems that by using useRef, you can define mutable values effectively. To put it simply, it provides a behavior similar to this in a class.

Summary

In conclusion, by using useRef, you can define values that are updatable. I come across these cases every once in a while, and since it feels like a rather tricky solution, I want to make sure I don't forget it.

Reference

Discussion

nullnull

自分もこういうケース対応したことあるのですが、解決パターン違ってたので共有します!
※どっちが良いかはわからないです

  1. useEffectの第2引数を[fruit]にする
  2. useEffectのreturnに()=>removeEventListener設置
1
YENDYEND

@null さん
ご共有ありがとうございます!

基本的は依存配列に state 渡せよって話なので、あんまり上記のようなケースはないのですが、

本文の中で少しだけ触れてますが、null さんのおっしゃられてるのはこのパターンかなと思います。

state を依存配列に渡すと、state が更新されるたびに、useEffect のコールバック関数が実行されるので、state を依存配列に渡すことが正しいケースでは問題ありません。

今回の記事のケースですと、マウント時の一度だけuseEffect を実行したいので、依存配列を空にしたい時の対処法になりますね。

nullnull

返信ありがとうございます
記事上のコードだけでは依存配列にstateを含めない理由がわからず適当なコメントしちゃったなって反省です…
自分の中ではフォームでstate参照するかref参照するかみたいな話なのかなって思いました

1
ka2nka2n

useEffectの中でキャプチャした変数が更新されなくて困っていて、最終的にその値でstateを更新するたけであれば更新関数(例ではsetFruit)に値ではなく関数を渡す形式(setFruit(currentFruit => newFruit))でも良いかなと思いました。アラートくらいであればこの中でやれそうです。

さらに複雑なことをstateを更新せずに行う場合は、お書きになったようなuseRefを使うパターンがよさそうだと思いました!

採用する値とは別に選択した値もそれぞれstateに入れる事もありそうです(fruitとselectedFruitをそれぞれstateにする)

1