'How to fix violetion took 200ms when scrolling a block with message loading?

I load messages by 20 pieces, update the state when it reaches 0 on scroll and twist the block 20 messages back. But after a few scrolls, the page freezes and I get a warning in the console: [Violation] 'message' handler took 187ms

I tried e.preventDefault() - didn't work, e.stopPropagation() - similar. Please tell me what I did wrong?

onScroll={(e) => {
                    if(e.target.scrollTop < 1) {
                        const msgID = prevMessages.length ? parseInt(prevMessages[0].id) : parseInt(messages[0].id);
                        console.log(msgID);
                        socket.emit('getPrevMessages', {roomId, msgID});
                        e.target.scrollTo(0, e.target.querySelector('.direct-chat-msg:nth-child(20)').offsetTop);
                        e.stopPropagation();
                    }
                }}

Thanks.



Solution 1:[1]

import { useState, useCallback } from 'react';
function debounce(func, wait) {
  let timeout;
  return () => {
      if (timeout) {
          clearTimeout(timeout);
      }
      timeout = setTimeout(func, wait)
  }
}
const changeHandler = (e) => {
                  if(e.target.scrollTop < 1) {
                      const msgID = prevMessages.length ? parseInt(prevMessages[0].id) : parseInt(messages[0].id);
                      console.log(msgID);
                      socket.emit('getPrevMessages', {roomId, msgID});
                      e.target.scrollTo(0, e.target.querySelector('.direct-chat-msg:nth-child(20)').offsetTop);
                      e.stopPropagation();
                  }
              }
const debouncedChangeHandler = useCallback(
  debounce(changeHandler, 250)
, []);         
onScroll={ debouncedChangeHandler}

Solution 2:[2]

The working but my handler not update states messages and prevMessages all time two empty arrays

const debounce = (func, wait) => {
        let timeout;
        return (() => {
            if (timeout) {
                clearTimeout(timeout);
            }
            timeout = setTimeout(() => func(), wait)
        })();
    }

    const changeHandler = (e) => {
        console.log(e);
        if(e.target.scrollTop < 1) {
            const msgID = prevMessages.length ? parseInt(prevMessages[0].id) : parseInt(messages[0].id);
            console.log(msgID);
            socket.emit('getPrevMessages', {roomId, msgID});
            //e.stopPropagation();
        }
    }
    const debouncedChangeHandler = useCallback((e) => debounce(() => changeHandler(e), 250),[]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Vladimir Developer