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 ObrasView = () => {
  const { id } = useParams<{ id: string }>();
  const [errorID, setErrorID] = useState<boolean>(false);

  const [responseObraData, setResponseObraData] = useState<Obra | null>(null);

  const [planilhaData, setPlanilhaData] = useState<PlanilhaData | null>(null);
  const [planilhaItemData, setPlanilhaItemData] = useState<PlanilhaItemData[]>([]);

  const [medicoesInfo, setMedicoesInfo] = useState<Medicao[]>([]);
  const [lastMedicaoItem, setLastMedicaoItem] = useState<MedicaoItem[]>([]);
  const [nextMedicaoNum, setNextMedicaoNum] = useState<number>(1);
  const [currentMedicaoData, setCurrentMedicaoData] = useState<MedicaoItem[]>([]);
  const [acumuladoPercent, setAcumuladoPercent] = useState<string>('');

  const { tabValue } = useParams<{ tabValue: string }>();
  const [activeTab, setActiveTab] = useState<string | null>(tabValue || 'consolidado');
  const [fetchedMedicaoData, setFetchedMedicaoData] = useState<{ [key: string]: MedicaoItem[] }>(
    {}
  );

  // Para nova medição, dados já mergeados
  const [processedData, setProcessedData] = useState<MergedData[]>([]);
  const handleUpdateProcessedData = useCallback((newProcessedData: MergedData[]) => {
    setProcessedData(newProcessedData);
  }, []);

  // Busca por dados da Obra
  const fetchObra = useCallback(async () => {
    if (!id) return null;

    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;

      setResponseObraData(data);

      setAcumuladoPercent(((data.valorAcumulado / data.valorTotal) * 100).toFixed(2));

      if ((data.status ?? 0) > 1) {
        fetchMedicoes(data.id);
      }
      fetchPlanilha(data.id);
    };

    fetchData();
  }, [fetchObra]);

  const obraData = useMemo(() => responseObraData, [responseObraData]);

  // Busca por dados da Planilha
  const fetchPlanilha = async (obraID: string) => {
    const planilhasResponse = await client.graphql({
      query: planilhasByObraID,
      variables: { obraID: obraID },
    });

    const planilhasData = planilhasResponse.data.planilhasByObraID.items;
    setPlanilhaData(planilhasData[0]);

    const itemsResponse = (await client.graphql({
      query: planilhaItemsByPlanilhaID,
      variables: { planilhaID: planilhasData[0].id, limit: 1500 },
    })) as unknown as { data: { planilhaItemsByPlanilhaID: { items: PlanilhaItemData[] } } };

    const itemsData = itemsResponse.data.planilhaItemsByPlanilhaID.items;
    const itemsDataSorted = itemsData.sort(
      (a, b) => new Date(a.createdAt ?? '').getTime() - new Date(b.createdAt ?? '').getTime()
    );
    setPlanilhaItemData(itemsDataSorted);
  };

  // Busca por Medições desta Obra
  const fetchMedicoes = async (obraID: string) => {
    const medicaoResponse = await client.graphql({
      query: medicoesByObraID,
      variables: { obraID: obraID },
    });

    const medicaoData = medicaoResponse.data.medicoesByObraID.items;

    // Se encontrou medições, salva resultados e busca dados da última medição
    if (medicaoData.length > 0) {
      setNextMedicaoNum(medicaoData.length + 1);
      medicaoData.sort((a, b) => a.medicaoNum - b.medicaoNum);

      const medicoesInfoConverted: Medicao[] = medicaoData.map((item) => ({
        id: item.id ?? '',
        medicaoNum: item.medicaoNum ?? 0,
        dataMedicao: item.dataMedicao ?? '',
        userCreatedAt: item.userCreatedAt ?? '',
        valorTotal: item.valorTotal ?? 0,
        valorTotalMaodeObra: item.valorTotalMaodeObra ?? 0,
        valorTotalMaterial: item.valorTotalMaterial ?? 0,
        valorAcumulado: item.valorAcumulado ?? 0,
        valorSaldo: item.valorSaldo ?? 0,
      }));
      setMedicoesInfo(medicoesInfoConverted);

      const lastMedicao = medicaoData[medicaoData.length - 1];
      const lastMedicaoResponse = await client.graphql({
        query: medicoesItemsByMedicaoID,
        variables: { medicaoID: lastMedicao.id, limit: 500 },
      });
      const lastMedicaoData = lastMedicaoResponse.data.medicoesItemsByMedicaoID.items;

      const lastMedicaoDataItems: MedicaoItem[] = lastMedicaoData.map((item) => ({
        item: item.item ?? '',
        qtdMedicao: Number(item.qtdMedicao),
        valorTotal: item.valorTotal ?? null,
        valorTotalPerc: item.valorTotalPerc ?? null,
        acumulado: item.acumulado ?? null,
        acumuladoPerc: item.acumuladoPerc ?? null,
        saldoQtd: item.saldoQtd ?? null,
        saldoValor: item.saldoValor ?? null,
        saldoValorPerc: item.saldoValorPerc ?? null,
      }));
      setLastMedicaoItem(lastMedicaoDataItems);
    }
  };

  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 },
      });

      const currentMedicaoData = response.data.medicoesItemsByMedicaoID.items;
      window.log('currentMedicaoData', currentMedicaoData);

      const medicaoDataConverted: MedicaoItem[] = currentMedicaoData.map((item) => ({
        item: item.item ?? '',
        qtdMedicao: item.qtdMedicao ?? null,
        valorTotal: item.valorTotal ?? null,
        valorTotalPerc: item.valorTotalPerc ?? null,
        acumulado: item.acumulado ?? null,
        acumuladoPerc: item.acumuladoPerc ?? null,
        saldoQtd: item.saldoQtd ?? null,
        saldoValor: item.saldoValor ?? null,
        saldoValorPerc: item.saldoValorPerc ?? null,
      }));

      // Armazena os dados buscados no estado fetchedMedicaoData
      setFetchedMedicaoData((prevState) => ({
        ...prevState,
        [medicaoID]: medicaoDataConverted,
      }));

      setCurrentMedicaoData(medicaoDataConverted);
    }
  };

  const showTabMedicao = useCallback((medicaoNum: number, medicaoID: string) => {
    setCurrentMedicaoData([]);
    setActiveTab(`medicao_${medicaoNum}`);
    handleMedicaoChange(medicaoID);
  }, []);

  if (!id || errorID)
    return (
      <Card p="5" shadow>
        <h4 className="text-center">Obra não encontrada!</h4>
      </Card>
    );

  const statusBackground = bgStatus[obraData?.status ?? 5];

  const classes = {
    titleBlock: 'p-5 border-b border-white-light min-h-[110px]',
    progressBlock: `gap-5 p-5 ${statusBackground}`,
    acumuladoPercent: 'font-display font-bold text-white lg:text-5xl text-4xl',
    tab: `relative text-base mx-0.5 border border-gray-200 z-10`,
    toActiveTab: `mt-1 border-b-2 hover:bg-gray-100 bg-white`,
    activeTab: 'bg-blue-500 border-blue-500 text-white hover:bg-blue-600',
  };

  if (!obraData)
    return (
      <>
        <Skeleton visible={true} height={288} radius="md"></Skeleton>
      </>
    );

  return (
    <>
      <Card p="0" shadow>
        <Bloco horizontal alignVertical="middle" justify="between" className={classes.titleBlock}>
          <Bloco vertical>
            <h2 className="text-sky-900">{obraData?.nomeObra}</h2>
            {obraData?.contrato && (
              <p className="text-sm text-slate-600">Contrato: {obraData?.contrato}</p>
            )}
          </Bloco>
          <Bloco vertical alignVertical="middle" alignHorizontal="center" className="gap-2">
            <BadgeStatus status={Number(obraData?.status)} icon size="lg" />
            <h4 className="text-blue-900">{obraData?.Campus?.nomeCampus}</h4>
          </Bloco>
        </Bloco>

        {/* Bloco de progresso */}
        <Bloco horizontal justify="between" className={classes.progressBlock}>
          {/* Cards de Datas */}
          {obraData?.dataInicio && obraData?.dataFim && (
            <Card p="4" className="basis-3/6 max-lg:basis-4/6 justify-between">
              <CardCountDays obraData={obraData} />
            </Card>
          )}

          {medicoesInfo.length > 0 && (
            <Card shadow withBorder className="basis-2/6">
              <small>Última Medição</small>
              <span className="lead mt-2">
                {dayjs(medicoesInfo[medicoesInfo.length - 1]?.dataMedicao).format('DD.MM.YY')}
              </span>
              <p>{medicoesInfo[medicoesInfo.length - 1]?.userCreatedAt}</p>
            </Card>
          )}

          {obraData?.status === 0 && (
            <Card shadow withBorder p="3" className="basis-2/6">
              <CardAddDesconto tableData={planilhaItemData} obraID={id} />
            </Card>
          )}

          {obraData?.status === 1 && (
            <Card shadow withBorder p="3" className="basis-3/6">
              <CardSetStart
                dataPrevista={obraData.dataInicio}
                obraID={id}
                duracao={obraData.duracao}
              />
            </Card>
          )}

          {acumuladoPercent !== '0.00' && (
            <Bloco
              vertical
              alignHorizontal="right"
              alignVertical="middle"
              className="max-lg:basis-1/6 basis-3/6"
            >
              <span className={classes.acumuladoPercent}>{acumuladoPercent}%</span>
              <small className="text-white">Completo</small>
            </Bloco>
          )}
        </Bloco>
        <MainProgressBar
          acumuladoPercent={acumuladoPercent}
          valorTotalObra={obraData?.valorTotal ?? 100}
          medicoesInfo={medicoesInfo}
        />
      </Card>

      <Content className="px-3 mt-[86px]">
        <Tabs className="w-full -mt-[76px]" radius="md" value={activeTab} onChange={setActiveTab}>
          {/* Tabs  */}
          <Tabs.List className="z-20">
            <Tabs.Tab
              value="consolidado"
              className={`${classes.tab} ${
                activeTab === 'consolidado' ? classes.activeTab : classes.toActiveTab
              } ml-0`}
              onClick={() => setActiveTab('consolidado')}
            >
              Consolidado
            </Tabs.Tab>
            <Tabs.Tab
              value="planilha"
              className={`${classes.tab} ${
                activeTab === 'planilha' ? classes.activeTab : classes.toActiveTab
              }`}
              onClick={() => setActiveTab('planilha')}
            >
              Planilha Orçamentária
            </Tabs.Tab>
            {medicoesInfo.map((medicao) => (
              <Tabs.Tab
                key={medicao.medicaoNum}
                value={`medicao_${medicao.medicaoNum}`}
                className={`${classes.tab} ${
                  activeTab === `medicao_${medicao.medicaoNum}`
                    ? classes.activeTab
                    : classes.toActiveTab
                }`}
                onClick={() => showTabMedicao(medicao.medicaoNum, medicao.id)}
              >
                Medição {medicao.medicaoNum}
              </Tabs.Tab>
            ))}
            {Number(obraData?.status) > 1 && acumuladoPercent !== '100.00' && (
              <Tabs.Tab
                value="add_medicao"
                className={`${classes.tab} ${
                  activeTab === 'add_medicao' ? classes.activeTab : classes.toActiveTab
                } text-lg font-bold mr-0`}
                onClick={() => setActiveTab('add_medicao')}
                ml="auto"
                leftSection={<Icon name="BiSolidAddToQueue" propsIcon={{ size: 24 }} />}
              >
                Nova Medição
              </Tabs.Tab>
            )}
          </Tabs.List>

          {/* Conteúdo Tabs */}
          <Tabs.Panel value="consolidado">
            <h3 className="text-blue-900 py-6 px-2">Resumo da Obra com Medições</h3>
            <ViewConsolidado
              planilhaItemData={planilhaItemData}
              medicoesInfo={medicoesInfo}
              medicoesItemData={lastMedicaoItem}
              showTabMedicao={showTabMedicao}
            />
          </Tabs.Panel>

          <Tabs.Panel value="planilha">
            <h3 className="text-blue-900 py-5 px-2">Planilha Orçamentária Original</h3>
            {activeTab === 'planilha' && obraData && planilhaData && (
              <ViewPlanilhaOrcamentaria
                planilhaData={planilhaData!}
                planilhaItemData={planilhaItemData}
                obraData={obraData}
              />
            )}
          </Tabs.Panel>

          {medicoesInfo.map((medicao) => (
            <Tabs.Panel value={`medicao_${medicao.medicaoNum}`} key={medicao.medicaoNum}>
              <h3 className="text-blue-900 py-5 px-2">Dados da Medição {medicao.medicaoNum}</h3>
              <ViewMedicao
                medicaoData={currentMedicaoData}
                medicaoInfo={medicao}
                planilhaItemData={planilhaItemData}
              />
            </Tabs.Panel>
          ))}

          {activeTab === 'add_medicao' && (
            <Tabs.Panel value="add_medicao">
              <h3 className="text-blue-900 py-5 px-2">Nova Medição</h3>
              <AddMedicao
                tableData={planilhaItemData}
                medicoesData={lastMedicaoItem}
                obraID={id}
                dataInicio={obraData?.dataInicio || Date.now().toString()}
                nextMedicaoNum={nextMedicaoNum}
                processedData={processedData}
                onUpdateProcessedData={handleUpdateProcessedData}
              />
            </Tabs.Panel>
          )}
        </Tabs>
      </Content>
    </>
  );
};

export default ObrasView;
```