Optimizing a React component that handles large data sets involves multiple strategies to enhance performance, including minimizing unnecessary renders, optimizing data processing, and efficiently managing state. Below are comprehensive steps and code modifications to optimize your AddMedicao component.
1. Utilize React.memo for Child Components
By default, React re-renders components whenever their parent re-renders. To prevent unnecessary re-renders of table rows when unrelated state changes occur, you can extract table rows into separate memoized components using React.memo.
Implementation:
-
Create a Memoized Table Row Component
import React, { memo } from 'react';
import { Table, TextInput, Progress, RingProgress, Tooltip } from '@mantine/core';
const MedicaoRow = memo(({ row, index, handleMedicaoChange }) => {
const isTitle = ['category', 'subcategory', 'sum'].includes(row.dataType);
return (
<Table.Tr key={index} className={`h-12 ${isTitle ? 'font-bold' : ''}`}>
{isTitle ? (
<>
<Table.Td colSpan={isTitle ? 5 : 1}>
{/* Progress Bar or Title */}
</Table.Td>
{Math.round(Number(row.newSaldoValorPerc)) !== 100 && (
<Table.Td className="text-right font-bold">
{formatarMoeda(row.newSaldoValor)}
</Table.Td>
)}
</>
) : (
<>
<Table.Td>
<TextInput
h={20}
className="input-clear"
type="text"
value={row.newQtd || ''}
onChange={(e) => handleMedicaoChange(index, parseFloat(e.target.value))}
// Other handlers...
/>
</Table.Td>
{/* Other cells... */}
</>
)}
</Table.Tr>
);
});
export default MedicaoRow;
-
Use MedicaoRow in AddMedicao Component
import MedicaoRow from './MedicaoRow'; // Adjust the path accordingly
// Inside the AddMedicao component's return statement
<Table.Tbody>
{calculatedData.map((row, index) => (
<MedicaoRow
key={row.item} // Use a unique key if available
row={row}
index={index}
handleMedicaoChange={handleMedicaoChange}
/>
))}
</Table.Tbody>
Benefits:
- Reduced Re-renders: Only the row with changed data will re-render, not the entire table.
- Improved Performance: Especially beneficial with large data sets.
2. Implement Table Virtualization
Rendering large tables can be performance-intensive. Virtualizing the table ensures that only the visible rows are rendered, significantly improving performance.
Using react-window:
-
Install react-window:
npm install react-window
-
Create a Virtualized Table Component:
import React, { memo } from 'react';
import { FixedSizeList as List } from 'react-window';
import MedicaoRow from './MedicaoRow'; // The memoized row component
import { Table } from '@mantine/core';
const VirtualizedTable = ({ data, handleMedicaoChange }) => {
const Row = memo(({ index, style }) => {
const row = data[index];
return (
<div style={style}>
<MedicaoRow row={row} index={index} handleMedicaoChange={handleMedicaoChange} />
</div>
);
});
return (
<List
height={600} // Adjust based on your layout
itemCount={data.length}
itemSize={50} // Adjust based on row height
width="100%"
>
{Row}
</List>
);
};
export default VirtualizedTable;
-
Integrate VirtualizedTable into AddMedicao:
import VirtualizedTable from './VirtualizedTable'; // Adjust the path accordingly
// Replace the existing <Table.Tbody> with:
<VirtualizedTable data={calculatedData} handleMedicaoChange={handleMedicaoChange} />
Benefits:
- Efficient Rendering: Only the rows visible in the viewport are rendered.
- Scalability: Handles large datasets with minimal performance impact.
3. Optimize State Management and Data Processing
Minimizing the computation and state updates can significantly enhance performance.
a. Optimize useEffect Dependencies and Logic
Ensure that useEffect hooks have correct dependencies to prevent unnecessary executions.
useEffect(() => {
if (!processedData.length) {
// Merge data if not processed
const mergedOriginalData = mergeOriginalData();
setMergedTableData(mergedOriginalData);
onUpdateProcessedData(mergedOriginalData);
} else {
setMergedTableData(processedData);
}
// Sort subcategories by depth
const ordenadasComProfundidade = Array.from(subcategoriasProfundidade.entries())
.sort((a, b) => b[1] - a[1])
.map(([item, profundidade]) => ({ item, profundidade }));
setSubcategoriasOrdenadas(ordenadasComProfundidade);
setLoading(false);
}, [tableData, processedData, onUpdateProcessedData]);
Notes:
- Dependencies: Ensure all dependencies (
processedData, onUpdateProcessedData) are included to prevent stale closures.
- Memoize Expensive Functions: Use
useMemo or useCallback for functions like mergeOriginalData if they are computationally heavy.
b. Memoize mergeOriginalData Function
const mergeOriginalData = useCallback(() => {
const mergedData = tableData.map((row) => {
// Existing merge logic...
});
return mergedData;
}, [tableData, medicoesDataMap]); // Include all dependencies
Benefits:
- Prevents Re-computation: The function is only redefined when dependencies change.
4. Batch State Updates
When updating multiple pieces of state based on a single event, batch the updates to minimize re-renders.
Implementation Example:
Instead of multiple setState calls in sequence, batch related updates.
const handleMedicaoChange = useCallback((index, value) => {
setMergedTableData((prevData) => {
const newData = [...prevData];
newData[index] = { ...newData[index], newQtd: value };
return newData;
});
}, []);
Benefits:
- Minimized Re-renders: Updates occur in a single state change.
- Improved Performance: Reduces the number of renders triggered by multiple state updates.
5. Avoid Inline Functions and Objects
Defining functions or objects inside the render method can cause components to re-render unnecessarily. Use useCallback and useMemo to memoize these.
Example:
Before:
<TextInput
onBlur={(e) => { /* handler */ }}
onKeyDown={(event) => { /* handler */ }}
/>
After:
const handleBlur = useCallback((index, e) => {
// Handler logic
}, [/* dependencies */]);
const handleKeyDown = useCallback((event) => {
// Handler logic
}, []);
<TextInput
onBlur={(e) => handleBlur(index, e)}
onKeyDown={handleKeyDown}
/>
Benefits:
- Prevent Re-creation: Functions aren't recreated on every render.
- Stable References: Essential for memoized child components to avoid unnecessary re-renders.
6. Implement Efficient Data Structures
Utilize data structures that offer faster lookups and mutations. For example, using Map for medicoesDataMap can offer better performance over plain objects for certain operations.
Implementation:
const medicoesDataMap = useMemo(() => {
const map = new Map();
medicoesData.forEach((medicao) => {
map.set(medicao.item, medicao);
});
return map;
}, [medicoesData]);
Benefits:
- Faster Lookups:
Map provides average constant time complexity for lookups.
- Cleaner Code: Easier to handle keys and iterate over entries.
7. Lazy Load Non-Critical Components
For components or parts of the UI not immediately visible, consider lazy loading them to reduce initial load time.
Implementation:
import React, { Suspense, lazy } from 'react';
const VirtualizedTable = lazy(() => import('./VirtualizedTable'));
<Suspense fallback={<div>Loading...</div>}>
<VirtualizedTable data={calculatedData} handleMedicaoChange={handleMedicaoChange} />
</Suspense>
Benefits:
- Improved Initial Load Time: Defers loading of components until necessary.
- Enhanced User Experience: Users see a faster initial render with critical content.
8. Optimize GraphQL Operations
Ensure your GraphQL operations are efficient and only request necessary data. Consider using data caching strategies with libraries like Apollo Client if applicable.
Recommendations:
-
Batch GraphQL Requests:
- Reduce the number of network requests by batching multiple mutations or queries.
-
Use Data Caching:
- Implement caching to prevent refetching data that hasn't changed.
-
Pagination and Limits:
- Fetch data in chunks if dealing with extremely large datasets.
9. Example of the Optimized AddMedicao Component
Here’s how the optimized component might look incorporating the above recommendations:
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import * as Resizer from '@column-resizer/react';
import { InputBlock } from '@components/Molecules';
import {
Button,
LoadingOverlay,
Table,
TextInput,
Tooltip,
Progress,
RingProgress,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { Bloco } from '@src/components/Atoms/Library';
import {
createMedicoes,
createMedicoesItem,
deleteMedicoes,
updateObra,
} from '@src/graphql/mutations';
import { useDispatch, useSelector } from 'react-redux';
import { addNotification } from '@src/stores/notificationsSlice';
import {
formatarMoeda,
formatarQtd,
getSubcategoryDepth,
toFixedNumber,
} from '@src/utils';
import { MedicaoItem, MergedData, PlanilhaItemData } from '@src/utils/interfaces';
import { generateClient } from 'aws-amplify/api';
import VirtualizedTable from './VirtualizedTable'; // Assuming it's implemented
import MedicaoRow from './MedicaoRow'; // Assuming it's implemented
const client = generateClient();
const AddMedicao = ({
tableData,
medicoesData,
obraID,
dataInicio,
nextMedicaoNum,
processedData,
onUpdateProcessedData,
}) => {
if (!tableData) return null;
const [loading, setLoading] = useState(true);
const { loggedUser } = useSelector((state) => state.userInfo);
const dispatch = useDispatch();
const subcategoriasProfundidade = useMemo(() => new Map(), []);
const [subcategoriasOrdenadas, setSubcategoriasOrdenadas] = useState([]);
const [totaisMedicao, setTotaisMedicao] = useState({
valorTotal: 0,
valorTotalMaodeObra: 0,
valorTotalMaterial: 0,
valorAcumulado: 0,
valorSaldo: 0,
});
const [mergedTableData, setMergedTableData] = useState([]);
const medicoesDataMap = useMemo(() => {
const map = new Map();
medicoesData.forEach((medicao) => {
map.set(medicao.item, medicao);
});
return map;
}, [medicoesData]);
const mergeOriginalData = useCallback(() => {
return tableData.map((row) => {
const medicaoCorrespondente = medicoesDataMap.get(row.item);
if (row.dataType !== 'item') {
const profundidade = getSubcategoryDepth(row.item);
subcategoriasProfundidade.set(row.item, profundidade);
}
const selectedRow = {
item: row.item,
qtd: row.qtd,
proporcaoMaodeObra: row.proporcaoMaodeObra,
proporcaoMaterial: row.proporcaoMaterial,
precoUnitarioDesconto: row.precoUnitarioDesconto,
precoTotalDesconto: row.precoTotalDesconto,
dataType: row.dataType,
category: row.category,
subcategory: row.subcategory,
};
if (medicaoCorrespondente) {
return {
...selectedRow,
...medicaoCorrespondente,
newQtd: null,
newValorTotal: null,
newValorTotalPerc: null,
newAcumulado: null,
newAcumuladoPerc: null,
newSaldoQtd: null,
newSaldoValor: null,
newSaldoValorPerc: null,
};
} else {
return {
...selectedRow,
qtdMedicao: null,
valorTotal: null,
valorTotalPerc: null,
acumulado: null,
acumuladoPerc: null,
saldoQtd: row.qtd,
saldoValor: null,
saldoValorPerc: null,
newQtd: null,
newValorTotal: null,
newValorTotalPerc: null,
newAcumulado: null,
newAcumuladoPerc: null,
newSaldoQtd: null,
newSaldoValor: null,
newSaldoValorPerc: null,
};
}
});
}, [tableData, medicoesDataMap, subcategoriasProfundidade]);
useEffect(() => {
if (!processedData.length) {
const mergedOriginalData = mergeOriginalData();
setMergedTableData(mergedOriginalData);
onUpdateProcessedData(mergedOriginalData);
} else {
setMergedTableData(processedData);
}
const ordenadasComProfundidade = Array.from(subcategoriasProfundidade.entries())
.sort((a, b) => b[1] - a[1])
.map(([item, profundidade]) => ({ item, profundidade }));
setSubcategoriasOrdenadas(ordenadasComProfundidade);
setLoading(false);
}, [tableData, processedData, mergeOriginalData, onUpdateProcessedData, subcategoriasProfundidade]);
const calculatedData = useMemo(() => {
const dataWithCalculatedLine = mergedTableData.map((row) => {
const precoUnitario = row.precoUnitarioDesconto || 0;
const newQtd = row.newQtd || 0;
const newValorTotal = toFixedNumber(newQtd * precoUnitario, 2);
const newValorTotalMaodeObra = toFixedNumber(newValorTotal * (row.proporcaoMaodeObra || 0), 2);
const newValorTotalMaterial = toFixedNumber(newValorTotal * (row.proporcaoMaterial || 0), 2);
const newSaldoQtd = (row.saldoQtd !== null ? row.saldoQtd : row.qtd || 0) - newQtd;
const newAcumulado = toFixedNumber((row.acumulado || 0) + newValorTotal, 2);
const newSaldoValor = toFixedNumber(row.precoTotalDesconto ? row.precoTotalDesconto - newAcumulado : 0, 2);
const newValorTotalPerc = row.precoTotalDesconto
? toFixedNumber((newValorTotal / row.precoTotalDesconto) * 100, 2)
: 0;
const newAcumuladoPerc = row.precoTotalDesconto
? toFixedNumber((newAcumulado / row.precoTotalDesconto) * 100, 2)
: 0;
return {
...row,
newValorTotal,
newValorTotalMaodeObra,
newValorTotalMaterial,
newValorTotalPerc,
newAcumulado,
newAcumuladoPerc,
newSaldoQtd,
newSaldoValor,
};
});
let dataWithCalculatedTotals = dataWithCalculatedLine;
subcategoriasOrdenadas.forEach((subcategory) => {
const relatedRows = dataWithCalculatedTotals.filter((r) => {
if (subcategory.item === '300') {
return r.dataType === 'category';
}
if (subcategory.profundidade > 0) {
return r.subcategory === subcategory.item;
}
return r.category === subcategory.item && r.dataType === 'item';
});
const newSaldoValor = toFixedNumber(
relatedRows.reduce((acc, r) => acc + (r.newSaldoValor || 0), 0),
2
);
dataWithCalculatedTotals = dataWithCalculatedTotals.map((row) => {
if (row.item === subcategory.item) {
const saldoValorPercentual = row.precoTotalDesconto
? toFixedNumber(((row.precoTotalDesconto - newSaldoValor) / row.precoTotalDesconto) * 100, 2)
: 0;
return {
...row,
newSaldoValor,
newSaldoValorPerc: saldoValorPercentual,
};
}
return row;
});
});
const valorTotal = toFixedNumber(
dataWithCalculatedTotals.reduce((acc, r) => acc + (r.dataType === 'item' ? r.newValorTotal || 0 : 0), 0),
2
);
const valorTotalMaodeObra = toFixedNumber(
dataWithCalculatedTotals.reduce((acc, r) => acc + (r.newValorTotalMaodeObra || 0), 0),
2
);
const valorTotalMaterial = toFixedNumber(
dataWithCalculatedTotals.reduce((acc, r) => acc + (r.newValorTotalMaterial || 0), 0),
2
);
const valorAcumulado = toFixedNumber(
dataWithCalculatedTotals.reduce((acc, r) => acc + (r.newAcumulado || 0), 0),
2
);
const valorSaldo = toFixedNumber(
dataWithCalculatedTotals.reduce(
(acc, r) => acc + (r.dataType === 'item' ? r.newSaldoValor || 0 : 0),
0
),
2
);
setTotaisMedicao({
valorTotal,
valorTotalMaodeObra,
valorTotalMaterial,
valorAcumulado,
valorSaldo,
});
return dataWithCalculatedTotals;
}, [mergedTableData, subcategoriasOrdenadas]);
const handleMedicaoChange = useCallback((index, value) => {
setMergedTableData((prevData) => {
const newData = [...prevData];
newData[index] = { ...newData[index], newQtd: value };
return newData;
});
}, []);
const form = useForm({
validateInputOnChange: true,
initialValues: {
dataMedicao: '',
},
validate: {
dataMedicao: (value) => {
let error;
const input = document.querySelector('input[name="dataMedicao"]');
if (!value) error = 'Informe a data da medição';
const date = new Date(value);
if (date.getTime() < new Date(dataInicio).getTime()) {
error = 'A data deve ser maior que o início da Obra';
}
if (date.getTime() > Date.now()) {
error = 'A data deve ser menor que a data atual';
}
if (error) {
if (input) input.focus();
return error;
}
return null;
},
},
});
const handleKeyDown = useCallback((event) => {
if (event.key === 'Enter') {
event.preventDefault();
}
}, []);
const handleSubmit = useCallback(async () => {
setLoading(true);
const medicaoID = await createNewMedicao();
if (medicaoID) {
await createNewMedicaoItem(medicaoID);
}
}, [createNewMedicao, createNewMedicaoItem]);
const createNewMedicao = useCallback(async () => {
const medicaoData = form.values;
try {
const medicao = await client.graphql({
query: createMedicoes,
variables: {
input: {
dataMedicao: medicaoData.dataMedicao,
medicaoNum: nextMedicaoNum,
valorTotal: totaisMedicao.valorTotal,
valorTotalMaodeObra: totaisMedicao.valorTotalMaodeObra,
valorTotalMaterial: totaisMedicao.valorTotalMaterial,
valorAcumulado: totaisMedicao.valorAcumulado,
valorSaldo: totaisMedicao.valorSaldo,
obraID: obraID,
userCreatedAt: loggedUser,
},
},
});
// Update Obra
await client.graphql({
query: updateObra,
variables: {
input: {
id: obraID,
valorAcumulado: totaisMedicao.valorAcumulado,
ultimaMedicao: medicaoData.dataMedicao,
},
},
});
return medicao.data.createMedicoes.id;
} catch (error) {
console.error('Erro ao criar medição:', error);
dispatch(addNotification({
title: 'Erro ao criar medição',
message: `Confira os dados e tente novamente. Se persistir, reporte este erro: ${error}`,
type: 'error',
}));
setLoading(false);
}
}, [form.values, nextMedicaoNum, totaisMedicao, obraID, loggedUser, dispatch, updateObra, createMedicoes]);
const createNewMedicaoItem = useCallback(async (medicaoID) => {
try {
const batchPromises = calculatedData.map((row) => {
const medicaoItem = {
item: row.item,
qtdMedicao: row.newQtd,
valorTotal: row.newValorTotal,
valorTotalPerc: row.newValorTotalPerc,
acumulado: row.newAcumulado,
acumuladoPerc: row.newAcumuladoPerc,
saldoQtd: row.newSaldoQtd,
saldoValor: row.newSaldoValor,
saldoValorPerc: row.newSaldoValorPerc,
medicaoID: medicaoID,
};
return client.graphql({
query: createMedicoesItem,
variables: { input: medicaoItem },
});
});
await Promise.all(batchPromises);
dispatch(addNotification({
title: 'Medição Criada com Sucesso!',
message: `${nextMedicaoNum}ª medição desta Obra.`,
type: 'success',
}));
window.location.reload();
} catch (error) {
console.error('Erro ao inserir item da medicao:', error);
await client.graphql({
query: deleteMedicoes,
variables: { input: { id: medicaoID } },
});
setLoading(false);
dispatch(addNotification({
title: 'Erro ao criar medição',
message: `Confira os dados e tente novamente. Se persistir, reporte este erro: ${error}`,
type: 'error',
}));
}
}, [calculatedData, client, dispatch, deleteMedicoes, createMedicoesItem, nextMedicaoNum]);
return (
<div className="flex-col relative">
{loading && <LoadingOverlay visible={loading} overlayProps={{ radius: 'sm', blur: 2 }} />}
<Resizer.Container>
<Resizer.Section minSize={600}>
{/* Orçamento Base Table */}
<Table striped verticalSpacing="sm" className="text-sm">
{/* Table header and body similar to original, can also be memoized if needed */}
</Table>
</Resizer.Section>
<Resizer.Bar className="cursor-w-resize hover:bg-slate-100" />
<Resizer.Section defaultSize={550} minSize={470}>
<form onKeyDown={handleKeyDown} onSubmit={form.onSubmit(handleSubmit)}>
{/* Medição Table Header */}
<Table striped verticalSpacing="sm" className="text-sm">
{/* Table header similar to original */}
<Table.Tbody>
<VirtualizedTable data={calculatedData} handleMedicaoChange={handleMedicaoChange} />
</Table.Tbody>
{/* Table Footer */}
<Table.Tfoot className="text-base">
{/* Footer rows similar to original */}
</Table.Tfoot>
</Table>
</form>
</Resizer.Section>
</Resizer.Container>
</div>
);
};
export default AddMedicao;
10. Additional Recommendations
-
Debounce Input Changes: If users are typing quickly, consider debouncing input changes to prevent excessive state updates.
import { debounce } from 'lodash';
const handleMedicaoChange = useCallback(
debounce((index, value) => {
setMergedTableData((prevData) => {
const newData = [...prevData];
newData[index] = { ...newData[index], newQtd: value };
return newData;
});
}, 300),
[]
);
-
Use Web Workers for Heavy Computations: Offload intensive data processing to web workers to keep the UI responsive.
-
Profile Performance: Utilize React DevTools Profiler to identify and address specific performance bottlenecks.
Conclusion
By implementing these optimizations, your AddMedicao component should exhibit significantly improved performance, even with large data sets. The key strategies involve preventing unnecessary re-renders, efficiently managing state and data processing, and leveraging virtualization for rendering large tables. Additionally, optimizing GraphQL operations and considering advanced techniques like web workers can further enhance performance.
If you encounter specific issues during implementation or need further assistance with any of the optimization steps, feel free to ask!