React 19’s useOptimistic hook causes re-render of an entire array

I am still learning and trying out the new features from React 19’s RC.
Recently I’ve started to work on a simple real-time chat-app.
This is how function that is ran using useActionState and uses useOptimistic looks like (inside of Textarea component):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const handleSubmit = (_prevState: string, queryData: FormData) => {
const message = queryData.get("message") as string;
if (user && message) {
startTransition(async () => {
addOptimisticMessage({
$id: "optimistic_message",
...
});
await submitAction(message, attachments);
});
}
};
</code>
<code>const handleSubmit = (_prevState: string, queryData: FormData) => { const message = queryData.get("message") as string; if (user && message) { startTransition(async () => { addOptimisticMessage({ $id: "optimistic_message", ... }); await submitAction(message, attachments); }); } }; </code>
const handleSubmit = (_prevState: string, queryData: FormData) => {
    const message = queryData.get("message") as string;
    if (user && message) {
      startTransition(async () => {
        addOptimisticMessage({
          $id: "optimistic_message",
          ...
        });
        await submitAction(message, attachments);
      });
    }
  };

This is where I actually initialize the useOptimistic inside of a Room component:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentState: MessageObject[], newMessage: MessageObject) => [
newMessage,
...currentState,
],
);
</code>
<code>const [optimisticMessages, addOptimisticMessage] = useOptimistic( messages, (currentState: MessageObject[], newMessage: MessageObject) => [ newMessage, ...currentState, ], ); </code>
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
    messages,
    (currentState: MessageObject[], newMessage: MessageObject) => [
      newMessage,
      ...currentState,
    ],
  );

And then this is how I map the array:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{optimisticMessages.map((message: MessageObject, index: number) => (
<Message key={message.$id} message={message} />
))}
</code>
<code>{optimisticMessages.map((message: MessageObject, index: number) => ( <Message key={message.$id} message={message} /> ))} </code>
{optimisticMessages.map((message: MessageObject, index: number) => (
  <Message key={message.$id} message={message} />
))}

Now to describe the problem:

  1. Optimistic message is added to the messages array without any problem, it doesn’t cause re-render of the other components.
    <- This works just fine and as expected.

  2. An actual message is added and the optimistic message is removed -> this is where the problem occurs as the optimistic message gets replaced by the actual one from database and a re-render of all the messages occurs.

Now, I am not updating the state of messages inside of the submitAction() function but I have a listener set up inside of the Room component that whenever a new message is added it updates the state.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>useEffect(() => {
if (room && room.$id) {
const unsubscribeMessages = client.subscribe(
`databases.${database}.collections.messages.documents`,
(response) => {
const payload = response.payload as MessageObject;
const messageRoomId = payload.room.$id;
console.log(payload);
if (messageRoomId === room.$id)
setMessages((prevMessages) => [payload, ...prevMessages]);
},
);
return () => {
unsubscribeMessages();
};
}
}, [room?.$id]);
</code>
<code>useEffect(() => { if (room && room.$id) { const unsubscribeMessages = client.subscribe( `databases.${database}.collections.messages.documents`, (response) => { const payload = response.payload as MessageObject; const messageRoomId = payload.room.$id; console.log(payload); if (messageRoomId === room.$id) setMessages((prevMessages) => [payload, ...prevMessages]); }, ); return () => { unsubscribeMessages(); }; } }, [room?.$id]); </code>
useEffect(() => {
    if (room && room.$id) {
      const unsubscribeMessages = client.subscribe(
        `databases.${database}.collections.messages.documents`,
        (response) => {
          const payload = response.payload as MessageObject;
          const messageRoomId = payload.room.$id;
          console.log(payload);
          if (messageRoomId === room.$id)
            setMessages((prevMessages) => [payload, ...prevMessages]);
        },
      );

      return () => {
        unsubscribeMessages();
      };
    }
  }, [room?.$id]);

^ When I comment out the addOptimistic() function in the Textarea component, it works just fine, so the cause of this re-render isn’t inside of this hook.

New contributor

Ninjonik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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