Blog>
Snippets

Implementing Debounce in Column Resizing

Provide a code snippet showing how to implement a debounce function for column resizing events in React to avoid performance issues caused by rapid state updates.
function debounce(fn, ms) {
  let timer;
  return () => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, ms);
  };
}
Defines a debounce function that delays execution of a function 'fn' until after 'ms' milliseconds have elapsed since the last time it was invoked. This helps in preventing performance issues caused by rapid state updates, such as during window resizing events that trigger column resizing.
const handleResize = debounce(() => {
  calculateResponsiveColumnSizes();
  setTableState((prevState) => ({
    ...prevState,
    columnSizing: calculateResponsiveColumnSizes(),
  }));
}, 200);
Creates a debounced version of a resize handler that recalculates column sizes and updates table state. The debounce function ensures that calculateResponsiveColumnSizes() is called only once every 200 milliseconds, reducing the frequency of state updates during rapid resize events.
useEffect(() => {
  window.addEventListener('resize', handleResize);
  return () => {
    window.removeEventListener('resize', handleResize);
  };
}, []);
Registers the debounced resize event handler to the window. This ensures that the table layout updates in response to window resizing, but in a performant manner thanks to the debouncing. It also includes cleanup logic to remove the event listener when the component unmounts, preventing memory leaks.