Join the discussion
Comments
Loading comments...
Cookie preferences
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Join the discussion
Loading comments...
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Comment React capture les erreurs dans l'arbre de composants et affiche une interface de secours.
Les limites d'erreur sont des composants classe React qui capturent les erreurs JavaScript n'importe où dans leur arbre de composants enfants, enregistrent ces erreurs et affichent une interface de secours au lieu de faire planter toute l'application. Elles fonctionnent comme un bloc catch{'} JavaScript, mais pour l'arbre de composants. Une limite d'erreur capture les erreurs pendant le rendu, dans les méthodes de cycle de vie et dans les constructeurs de tout l'arbre en dessous d'elle.
Lorsqu'un composant du sous-arbre lève une exception pendant le rendu (ou dans une méthode de cycle de vie), React commence à propager l'erreur vers le haut à travers l'arbre Fiber, cherchant la limite d'erreur la plus proche.
React remonte à travers les fibers parents. S'il trouve un composant classe qui implémente getDerivedStateFromError ou componentDidCatch, il s'arrête là. S'il atteint la racine sans en trouver, toute l'application se démonte.
React appelle getDerivedStateFromError(error) sur le composant classe limite. Cette méthode statique retourne un nouveau state (p. ex. '{' hasError: true '}') qui cause le re-rendu de la limite avec l'interface de secours.
Une fois l'interface de secours affichée, React appelle componentDidCatch(error, errorInfo) — un bon endroit pour envoyer l'erreur à un service de journalisation comme Sentry.
Le composant limite vérifie son state (hasError) et affiche soit les enfants (normal) soit un élément JSX de secours. Le reste de l'application en dehors de la limite continue de fonctionner normalement.
Méthode de classe statique. Appelée pendant la phase de rendu lorsqu'un enfant lève une exception. Retourne un nouveau state pour déclencher le rendu de secours.
Méthode d'instance. Appelée pendant la phase de commit après l'affichage de l'interface de secours. À utiliser pour la journalisation des erreurs. Reçoit l'erreur + la pile de composants.
Les erreurs remontent dans l'arbre Fiber jusqu'à la limite la plus proche, tout comme les exceptions remontent dans les piles d'appels.
Les limites peuvent être réinitialisées en changeant leur prop key, ce qui cause le démontage et remontage de tout le sous-arbre à neuf.
1class ErrorBoundary extends React.Component {2 state = { hasError: false, error: null };34 static getDerivedStateFromError(error) {5 // Called during render — must be pure, no side effects6 return { hasError: true, error };7 }89 componentDidCatch(error, info) {10 // Called after commit — safe for side effects like logging11 logErrorToSentry(error, info.componentStack);12 }1314 render() {15 if (this.state.hasError) {16 return <FallbackUI error={this.state.error} />;17 }18 return this.props.children;19 }20}2122// Usage:23<ErrorBoundary>24 <MyComponent /> {/* If this throws, ErrorBoundary catches it */}25</ErrorBoundary>
Sans limites d'erreur, une seule erreur de rendu non gérée fait planter toute votre application React et affiche un écran blanc. Les limites d'erreur vous permettent de mettre en quarantaine les défaillances dans des sections isolées de l'interface — le reste de l'application continue de fonctionner. C'est essentiel pour les applications en production où vous ne pouvez pas anticiper tous les cas limites.
Your e-commerce app crashes in production when a product with malformed data renders. The entire page goes white and users see nothing — you lose the sale and have no visibility into what happened.
Without error boundaries, a single component throwing an error unmounts the ENTIRE React tree. The user sees a blank page. No error tracking fires because the crash happened during rendering, not in a try/catch block.
Wrap critical sections in error boundaries with strategic granularity: one around the product card, one around the cart, one around the whole page. Use componentDidCatch to send the error + componentStack to Sentry. Show a helpful fallback UI ('Something went wrong, refresh to try again') instead of a blank page.
Takeaway: Error boundaries are your PRODUCTION safety net. Place them at route level (catch everything), feature level (isolate failures), and widget level (for third-party components you don't control). Always log to an error tracking service in componentDidCatch.
You embed a third-party analytics chart widget in your dashboard. After a library update, the widget occasionally throws during rendering due to unexpected data formats.
The chart crash cascades — it's nested inside your dashboard layout, so the error propagates up and takes down the entire dashboard, including the navigation, sidebar, and all other widgets.
Wrap ONLY the third-party widget in its own error boundary. The fallback shows a placeholder ('Chart unavailable — refresh to retry'). The rest of the dashboard remains fully functional. Users can still use all other features while you investigate the chart issue.
Takeaway: Error boundaries give you component-level fault isolation, similar to microservice circuit breakers. Treat each third-party or unstable component as an isolated fault domain.