본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Data Grid - 성능

원문 보기 위키 갱신

Data Grid - 성능 (Performance)

Data Grid의 성능을 개선하기 위해 다음 권장 사항을 따르세요.

출처: MUI X documentation

본문

Data Grid는 많은 요소를 렌더링하는 복잡한 컴포넌트라서, 불필요한 리렌더링을 유발하는 방식으로 성능 문제를 의도치 않게 만들기 쉽습니다. 이 가이드는 일반적인 문제를 피하기 위해 Data Grid를 구현하는 모범 사례를 설명합니다.

props를 전달할 때 안정적인 참조를 유지하세요 (Maintain a stable reference when passing props)

일반 원칙으로, 모든 비(非)원시 props는 불필요한 리렌더링을 피하기 위해 렌더링 사이에 안정적인 참조를 유지해야 합니다. 특히 columns prop이 중요합니다. 컬럼은 컴포넌트가 마운트된 이후에는 절대 변하지 않는 정의로 설계되었습니다. 그렇지 않으면 컬럼 너비나 순서 같은 요소를 잃을 위험이 있습니다.

안정적인 참조를 유지하는 방법은 두 가지입니다:

  1. 컬럼이 컴포넌트 범위 안의 어떤 것에도 의존하지 않는다면, 컴포넌트 밖에서 정의한 뒤 prop으로 전달할 수 있습니다:

    const columns = [
      { field: 'id' },
      { field: 'firstName' },
      { field: 'lastName' },
      { field: 'age' },
      { field: 'fullName' },
    ];
    
    function App() {
      return <DataGrid columns={columns} {...other} />;
    }
    
  2. 컬럼이 상태 값이나 prop 같은 컴포넌트 범위 안의 무언가를 필요로 한다면, useMemo() 훅을 사용해 렌더링 사이에 안정적인 참조를 유지할 수 있습니다:

    function App(props) {
      const renderCell = React.useCallback(
        (params) => {
          return (
            <strong>
              {params.value} {props.someValue}
            </strong>
          );
        },
        [props.someValue],
      );
    
      const columns = React.useMemo(
        () => [
          { field: 'id' },
          { field: 'firstName' },
          { field: 'lastName' },
          { field: 'age' },
          { field: 'fullName', renderCell },
        ],
        [renderCell],
      );
    
      return <DataGrid columns={columns} {...other} />;
    }
    

정적 객체를 추출하고 루트 props를 메모이즈하세요 (Extract static objects and memoize root props)

Data Grid 컴포넌트는 성능 최적화를 위해 React.memo를 사용하며, 이는 Grid와 그 하위 컴포넌트가 props가 변경될 때만 리렌더링된다는 뜻입니다. 하지만 Data Grid의 루트 props가 메모이즈되지 않으면 불필요한 리렌더링을 유발하기 매우 쉽습니다. 아래 예시에서 slots와 initialState 객체는 매 렌더링마다 다시 생성되므로, Data Grid 자체도 어쩔 수 없이 함께 리렌더링됩니다.

function Component(props) {
  return (
    <DataGrid
      rows={props.rows}
      slots={{
        row: CustomRow,
      }}
      cellModesModel={{ [props.rows[0].id]: { name: { mode: GridCellModes.Edit } } }}
    />
  );
}

리렌더링을 막는 한 가지 방법은 정적일 수 있는 객체는 추출하고, 다른 객체에 의존하는 객체는 메모이즈하는 것입니다. 이 원칙은 객체나 함수인 모든 prop에 적용됩니다.

const slots = {
  row: CustomRow,
};

function Component(props) {
  const cellModesModel = React.useMemo(
    () => ({ [props.rows[0].id]: { name: { mode: GridCellModes.Edit } } }),
    [props.rows],
  );

  return (
    <DataGrid rows={props.rows} slots={slots} cellModesModel={cellModesModel} />
  );
}

리렌더링 과정 시각화 (Visualizing the re-rendering process)

Data Grid는 불필요한 리렌더링을 피하기 위해 일부 하위 컴포넌트를 메모이즈합니다. 아래는 Grid와의 상호작용에 응답해 어떤 셀이 리렌더링되는지 보여 주는 시각화입니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import useForkRef from '@mui/utils/useForkRef';
import { DataGridPro, GridCell } from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';

const TraceUpdates = React.forwardRef<any, any>((props, ref) => {
  const { Component, ...other } = props;
  const rootRef = React.useRef<HTMLElement>(null);
  const handleRef = useForkRef(rootRef, ref);

  React.useEffect(() => {
    const root = rootRef.current;
    root!.classList.add('updating');
    root!.classList.add('updated');

    const timer = setTimeout(() => {
      root!.classList.remove('updating');
    }, 360);

    return () => {
      clearTimeout(timer);
    };
  });

  return <Component ref={handleRef} {...other} />;
});

const CellWithTracer = React.forwardRef((props, ref) => {
  return <TraceUpdates ref={ref} Component={GridCell} {...props} />;
}) as typeof GridCell;

const slots = {
  cell: CellWithTracer,
};

export default function GridVisualization() {
  const { data, loading } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 100,
    editable: true,
    maxColumns: 15,
  });

  return (
    <Box
      sx={(theme) => ({
        height: 400,
        width: '100%',
        '&&& .updated': {
          transition: theme.transitions.create(['background-color', 'outline'], {
            duration: theme.transitions.duration.standard,
          }),
        },
        '&&& .updating': {
          backgroundColor: 'rgb(92 199 68 / 20%)',
          outline: '1px solid rgb(92 199 68 / 35%)',
          outlineOffset: '-1px',
          transition: 'none',
        },
      })}
    >
      <DataGridPro
        {...data}
        loading={loading}
        rowHeight={38}
        checkboxSelection
        disableRowSelectionOnClick
        slots={slots}
      />
    </Box>
  );
}

API

더 알아보기 (Learn more)