0

I am developing a React Native app which has a chat as one of its main functions. I use a .useState([]) hook to store the chat's messages and FlatList to render the messages. When I am sending or receiving a message I do setMessages[...messages, {newMessageData}]. But after a certain amount of messages have been stored in the chat, it takes a while just to press send to a message (excluding server handling) until the message loads shows in the FlatList. How could I improve the performance so that it would function well enough for a good live chat?

 const [messages, setMessages] = React.useState([{datetime: new Date(), content: "", sender: "", num: "amfu", new:[]}])

const addMessage = (sender, content, id, hasImage, image) => {
    let data = {}
  
    if(messages.length >= 0){
        data = {"sender": sender, "content": content, "num": messages.length, 
        "read":true, "datetime": new Date(), "id": id, "reactions": {"user": "", "other": "", "has":false}, "hasImage": hasImage,
        "image": hasImage ? image : null}
    } else {

    }

    setMessages([data, ...messages])
    setText("")
  }


<FlatList 
      data={messages}   
      renderItem={handleM}
      keyExtractor={(item) => item.num} 
      inverted={true} 
      style={{maxHeight: "90%", height: "auto", paddingTop: 100,}}
      contentContainerStyle={{ flexGrow: 1 }}  
      ref={listRef}
      scrollEnabled={isLongPressed == ""} 
    />
3
  • It has to do with the way you are storing your messages, you need to share the structure and the body which you are sending when posting the message. Commented Dec 10, 2023 at 7:00
  • provide some code Commented Dec 11, 2023 at 6:07
  • I edited it to add code samples Commented Dec 12, 2023 at 17:20

1 Answer 1

0

When utilizing setState in React Native, each update triggers a complete screen re-render. In scenarios where extensive chat data is stored in a list, reloading this data with every re-render can become inefficient, especially as the dataset grows. While traditional solutions involve separating components to limit the scope of re-renders, the challenge persists with large lists.

To address this, I recommend incorporating the useMemo hook. This hook proves valuable when dealing with dynamic list data, allowing you to cache calculations between re-renders. Ensure that you encapsulate the relevant logic within a useMemo call at the highest level of your component. This optimization can significantly enhance performance, particularly as the size of the list increases.

React native - useMemo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.