This is a code from a React Application, that receive a large amount of data and displays in diverse ways, that can be in different internal tabs. But it's slow. I need an improvement for fix code mistakes and a better run:
import { Icon } from '@components/Atoms';
import { BadgeStatus } from '@components/Molecules';
import { Skeleton, Tabs } from '@mantine/core';
import { Bloco, Card, Content } from '@src/components/Atoms/Library';
import { CardCountDays } from '@src/components/Organisms/CardCountDays';
import { MainProgressBar } from '@src/components/Organisms/MainProgressBar';
import {
getObra,
medicoesByObraID,
medicoesItemsByMedicaoID,
planilhaItemsByPlanilhaID,
planilhasByObraID,
} from '@src/graphql/queries';
import { Medicao, MedicaoItem, Obra, PlanilhaData, PlanilhaItemData } from '@src/utils/interfaces';
import { bgStatus } from '@src/utils/interfaces/status.enum';
import { generateClient } from 'aws-amplify/api';
import dayjs from 'dayjs';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import { CardAddDesconto } from './obras.add-desconto';
import { AddMedicao, MergedData } from './obras.add-medicao';
import { CardSetStart } from './obras.set-start';
import { ViewConsolidado } from './obras.view-consolidado';
import { ViewMedicao } from './obras.view-medicao';
import { ViewPlanilhaOrcamentaria } from './obras.view-planilha';
const client = generateClient();
type Tabs = 'consolidado' | 'planilha' | 'add_medicao';
const response = (await client.graphql({
query: getObra,
variables: { id: id },
})) as unknown as { data: { getObra: Obra } };
if (!response.data.getObra) setErrorID(true);
return response.data.getObra as Obra;
}, [id]);
useEffect(() => {
const fetchData = async () => {
const data = await fetchObra();
if (!data) return;
const handleMedicaoChange = async (medicaoID: string) => {
// Verifica se os dados para o medicaoID atual já foram buscados
if (fetchedMedicaoData[medicaoID]) {
// Se os dados já existirem, use-os diretamente
setCurrentMedicaoData(fetchedMedicaoData[medicaoID]);
} else {
// Se os dados não existirem, faça a consulta ao banco de dados
const response = await client.graphql({
query: medicoesItemsByMedicaoID,
variables: { medicaoID: medicaoID, limit: 500 },
});
Improving the performance of a React application that handles large amounts of data involves several strategies, including optimizing data fetching, minimizing unnecessary re-renders, and efficiently managing state. Below are detailed recommendations along with a refactored version of your ObrasView component incorporating these improvements.
Key Improvements
Parallel Data Fetching:
Fetch medicoes and planilhas in parallel where possible to reduce waiting time.
Lazy Loading Tab Content:
Load the content of each tab only when it becomes active to prevent rendering all data upfront.
Memoization:
Utilize React.memo for child components to prevent unnecessary re-renders.
Use useMemo and useCallback effectively to memoize values and functions.
Efficient State Management:
Combine related state variables to reduce the number of state updates.
Utilize useReducer if the state logic becomes complex.
Optimizing GraphQL Queries:
Fetch only the necessary fields to reduce payload size.
Implement pagination or limits on data fetching if dealing with extremely large datasets.
Avoid Inline Functions in JSX:
Define functions outside of the render to prevent them from being recreated on every render.
Component Code Splitting:
Use React.lazy and Suspense to split code and load components on demand.
Refactored Code
Below is the refactored version of your ObrasView component incorporating the above improvements:
However, in the refactored code, fetching remains in sequence to ensure that dependent data is fetched appropriately, but this can be optimized further based on specific dependencies.
2. Lazy Loading Tab Content
Issue: All tab contents are loaded at once, which can be heavy if there are many tabs or the content is resource-intensive.
Solution: Utilize React.lazy and Suspense to load tab content only when the respective tab is active.
jsx
const ViewConsolidado = React.lazy(() => import('./obras.view-consolidado'));
// Similarly for other tab content components
// Use Suspense around the Tabs.Panel to show a fallback loader while the component loads
<Suspense fallback={<Skeleton visible height={200} radius="md" />}>
<Tabs.Panel value="consolidado">
{/* ... */}
</Tabs.Panel>
{/* Other Panels */}
</Suspense>
3. Memoization
Use React.memo:
Wrap the ObrasView component with React.memo to prevent re-renders when props haven't changed.
jsx
export default React.memo(ObrasView);
Use useMemo and useCallback:
Memoize derived values and functions that don't need to be recreated on every render.
Error Handling: Improve error handling by providing user-friendly messages and potentially retry mechanisms.
Logging: Remove or limit console logs (window.log) to prevent performance hits and clutter in production.
Performance Monitoring: Utilize React's Profiler and browser performance tools to identify and address other potential bottlenecks.
Conclusion
By implementing these optimizations, your React application should perform significantly better, especially when handling large datasets and complex UI interactions. The key is to load only what is necessary, prevent unnecessary re-renders, and manage state efficiently. Additionally, leveraging React's built-in features like React.memo, useMemo, useCallback, and lazy loading can lead to substantial performance gains.