reactjstypescriptchat

Swap component position without re-render


I'm making a react page for chat application with the UI as below image (Please ignore black box for sensor info)

Chat application UI

In this page, i'm create 2 separate components:

  1. The red border component to show list conversation. Each conversation is another component that be rendered by for loop.
  2. The blue border component to show list chat message.

Two above components have wrapped inside chat context that contains list conversation, chat messages data...

Chat mechanism implemented by using stomp client connect websocket to java spring boot server.

For the user experience (as other chat application), i want to sort the list conversation by time DESC, not only at init time, when new chat message come from any conversation, that conversation should be pushed on top.

Currently i'm using list.sortByTime().forEach() in JSX to generate list conversation. But when list conversation changed, whole page will re-render (include blue border component), that will make list message re-init, must be scroll to bottom, lost focus at type message input box, and its not convenient.

I have tried react memory but still not work and i expect that when new message come from a conversation, that conversation component should be push to top of list conversation without re-render blue border component.


Solution

  • From the useContext docs

    React automatically re-renders all the children that use a particular context starting from the provider that receives a different value. The previous and the next values are compared with the Object.is comparison. Skipping re-renders with memo does not prevent the children receiving fresh context values.

    If both your red and blue components consume the chat Context, then any change to that Context's value will re-render both components. Check out this answer on techniques to avoid re-renders when Context values are updated.