Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
When to use React Error Boundary Components?

When should we use Error Boundary components? Only for missing props and stuff like that?

For example, imagine this api fetching hook:

const useFetch = () => {
   ...
    
   const [error, setError] = useState(null);
 
   const method = async () => {
     try {
        await api.fetchData();
     } catch(err) {
       setError(err);
     }
   };

   useEffect(() => {
     method();
   },[]);

   return { ..., error };
}

Now, in a component, I just do:

const MyComponent = () => {
   const { error } = useFetch();

   if (error) return <FallbackUI />;

   return <MainUI />;
}

Can I use an ErrorBoundary component to handle this situation (api call errors) instead of conditionally rendering?

EDIT

And what about if I only want to display a fallback UI when my fetching data method fails and there any data was previously retrieved?

Something like:

const { data, getMoreData, error } = useFetchPosts(); // data is stateful inside the hook
  
if (error && !data) return <FallbackUI />;

return <MainUI data={data} />;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I've followed the following approach in my projects that are all hooks/functional component implementations.

I'm using https://github.com/bvaughn/react-error-boundary

import { ErrorBoundary } from "react-error-boundary";

<ErrorBoundary FallbackComponent={ErrorFallback}>
   <MyComponent />
</ErrorBoundary>   

//reject the promise so it gets bubbled up
const useFetch = () => {
   ...
    
   const [error, setError] = useState(null);
 
   const method = async () => {
     try {
        await api.fetchData();
     } catch(err) {
       // setError(err);
      return Promise.reject(err);
     }
   };

   useEffect(() => {
     method();
   },[]);

   return { ..., error };
}  


function ErrorFallback({ error }: { error: any }) {
  return (
    <>
      // you custom ui you'd like to return
    </>
  );
}  

EDIT:

I typically have this at the top level so this is typically a catch all for all the unhandled exceptions. In other words, I wrap my App.tsx in the root index.tsx file in an ErrorBoundary. So, my code looks more like this

 ...
 <ErrorBoundary FallbackComponent={ErrorFallback}>
    <SWRConfig ...>
       <React.StrictMode>
          <ScrollToTop></ScrollToTop>
             <App ... />
       </React.StrictMode>
      </SWRConfig>
  </ErrorBoundary>
   
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda