This is a react UI performance issue. I have a datachannel connection where I can read and write data to the server on my react UI. But I realized that the data streaming will trigger UI re-rendering and cause the UI to freeze. The code structure is like below:
export default function Parent() {
const [msg, setMsg] = useState<any>({
a: {...},
b: {
logs: []
}
})
const msgRef = useRef();
msgRef.current = msg;
//skip the code where I establish the datachannel...
const handleMsg = (data) => {
let newMsg = {...dcMessageRef.current};
newMsg = update(newMsg, {b: {logs: {$push: data}}}); // append the new data to the logs array.
setMesg(newMsg);
}
// Read the message from data channel.
useEffect(() => {
datachan.onmessage = event => {
const data = JSON.parse(new TextDecoder().decode(event.data));
handleMsg(data);
}
}, [datachan]);
return <>
<ChildA logs={msg.b.logs}></ChildA> // ChildA is a list to display the logs
<ChildB datachan={datachan}></ChildB> // ChildB is simply a component to send data through the datachan when user clicks a button.
</>
}
Basically, the logic is simple. I have a parent component with two children components. The parent component listens to a datachannel(webrtc datachannel. You could treat it as a socket.) When there is a new message, I update the parent's msg state variable to add this new logline to the log array.
ChildA simply display the log array with a list. ChildB will send messages to the datachannel(socket) when user clicks a button.
The issue is when the log streaming starts, when I click the button to send message to the other side, it delayed for a while(2-5 seconds). It feels like the logs streaming kept the UI re-rendering and blocked other activities. Please let me know where I did wrong and how I can solve the performance problem.