why is the useState hook being invoked twice?

The example below is intended to be a testcase demonstrating a duplicate hook for the following scenario:

  1. The user types in a query and presses the Send button
  2. A new Conversation object is initialized and added to the list existing conversations
  3. An invokeServerAPI function is called with the query as the parameter and the callback function to be invoked for each response steps. There may be multiple response steps for each query and I want to display them immediately as they come in from the server
  4. The response is added to the current conversation. However the setConversations hook is invoked twice for each step, even though updateCurrentConversation is called only once.

Console output:

page.tsx:25 Text response received: Response for query:sample query 1
page.tsx:31 Invoke updateCurrentConversation with response:  Response for query:sample query 1
page.tsx:31 Invoke updateCurrentConversation with response:  Response for query:sample query 1

Source:

"use client"

import React, { useState, useRef } from 'react';

export default function MyApp() {
  const [input, setInput] = useState('');
  const [conversations, setConversations] = useState([]);
  const messagesEndRef = useRef(null);

  const handleSubmit = async (event) => {
    event.preventDefault();

    const startTime = new Date()
    const newConversation = { query: input, startTime, responses: [] }
    setConversations((prevConversations) => [...prevConversations, newConversation]);

    try {
      await invokeServerAPI(input, textHandler)
    }
    finally {
      setInput('');
    }

    function textHandler(text) {
      console.log("Text response received:", text)
      updateCurrentConversation(text)
    }

    function updateCurrentConversation(data) {
      setConversations((prevConversations) => {
        console.log('Invoke updateCurrentConversation with response: ', data)
        const index = prevConversations.findIndex(conversation => conversation.startTime === startTime);
        const _newConversation = { ...prevConversations[index] };
        _newConversation.responses.push({ data })
        return [
          ...prevConversations.slice(0, index),
          _newConversation,
          ...prevConversations.slice(index + 1)
        ];
      });
    }
  };

  return (
    <div className="flex flex-col h-screen">
      <div className="overflow-y-scroll flex-grow p-2">
        {conversations.map((conversation, index) => (
          <div key={index} className="mb-5">
            <p>{conversation.startTime.toLocaleString()} <span className="font-bold">{conversation.query})</span>:</p>
            {conversation.responses
              .map((response, respIndex) => {
                return (
                  <div key={index * 1000 + respIndex} className="mb-2">
                      <pre className="mt-2 bg-gray-100 p-2 rounded border border-gray-300 whitespace-pre-wrap">{response.data}</pre>
                  </div>
                );
              })
            }
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>
      <div className="p-2 bg-gray-800 text-white">
        <form onSubmit={handleSubmit}>
          <div className="flex justify-start space-x-4">
            <div className="flex flex-col" style={{ marginRight: '1rem', marginLeft: '0' }}>
              <label className="text-black" style={{ color: 'black', display: 'block', width: 'auto' }}>Query:</label>
              <input
                type="text"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                className="p-2 bg-gray-300 text-black rounded-md"
                style={{ fontSize: '18px', color: 'black', height: '40px', width: '500px' }}
                placeholder="Enter your query here"
              />
            </div>
            <div className="flex flex-col items-start">
              <label style={{ color: 'black', display: 'block', width: 'auto' }}> </label>
              <button type="submit" className="bg-green-500 text-white rounded-md hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-opacity-50"
                style={{ paddingLeft: '1rem', paddingRight: '1rem', height: '40px', marginLeft: '0' }}>Send</button>
            </div>
          </div>
        </form>
      </div>
    </div >
  );
}

export function invokeServerAPI(theQuery, theHandler) {

  return new Promise((resolve, reject) => {

    //simulate just one response
    theHandler('Response for query:' + theQuery)
    resolve(null);
  })
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật