OvidijusParsiunas / deep-chat

Fully customizable AI chatbot component for your website
https://deepchat.dev
MIT License
1.27k stars 175 forks source link

Component is re-rendering when using useState in React #87

Closed easonoob closed 5 months ago

easonoob commented 5 months ago

When the ColorChanger button is clicked to change the color, it triggers a re-render of the DeepChatReact component. This re-render, in turn, causes the Chat component to also be re-rendered, resulting in the loss of its internal state, such as any unfinished text in the input box. However, if the DeepChatReact component is used without passing props, like , the unfinished text in the input box is preserved. This behavior suggests that the re-rendering of DeepChatReact due to prop changes is impacting the state of Chat.


import React, { useState } from 'react';
import { DeepChat as DeepChatReact, DeepChat } from 'deep-chat-react';

const ColorChanger = ({ onChangeColor }) => {
  const getRandomColor = () => {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  };

  const handleChangeColor = () => {
    const newColor = getRandomColor();
    onChangeColor(newColor);
  };

  return (
    <button
      className="btn-round mr-1"
      color="neutral"
      target="_blank"
      outline
      onClick={handleChangeColor}
    >
      Change Color
    </button>
  );
};

const Chat = ({ index, onClose }) => {
  const [color, setColor] = useState('lightblue');

  const componentStyle = {
    width: '98%',
    height: '90%',
    position: "fixed",
    bottom: "1%",
    borderRadius: "10px",
    zIndex: 10,
    left: "1%",
    backgroundColor: color,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    boxShadow: "0 0 10px rgba(0, 0, 0, 0.15)"
  };

  return (
    <div style={componentStyle}>
      <DeepChatReact  request={"request"} stream={{ simulation: 31 }}/>
      <ColorChanger onChangeColor={setColor} />
    </div>
  );
};
export default Chat;
OvidijusParsiunas commented 5 months ago

Hi @easonoob. I'm not 100% sure what you mean by the comment or what the question is, could you perhaps elaborate on the issue.

If you are referring to the fact that React re-renders the component when you use useState, I have discussed this topic in the following issue.

Let me know if you need further help. Thanks!

easonoob commented 5 months ago

yes react re-renders , I'm following #61

OvidijusParsiunas commented 5 months ago

I'm going to close this issue as the conversation on this topic should be continued in the following issue. Thanks!