Recover from rendering errors with boundaries
A boundary isolates a failing subtree
An Error Boundary is a component that React can use to replace failed descendant UI with a fallback. A class implements static getDerivedStateFromError to derive fallback state and can implement componentDidCatch to report the error. A boundary can surround function or class descendants. Place it at a useful recovery boundary (a panel, route or section), not around every button by default. Error Boundaries do not replace validation or loading states.
import React,{Component,useState} from 'react';class InspectionBoundary extends Component { state={failed:false}; static getDerivedStateFromError(){return {failed:true};} componentDidCatch(error,info){console.info('Synthetic panel failed',info.componentStack);} render(){return this.state.failed?<section><p role="alert">Inspection unavailable.</p><button type="button" onClick={this.props.onRetry}>Retry with safe record</button></section>:this.props.children;}}function Inspection({record}){if(!record)throw new Error('Synthetic record missing');return <p>Inspection: {record.name}</p>;}export default function App(){const [record,setRecord]=useState({name:'Clamp'});const [attempt,setAttempt]=useState(0);function retry(){setRecord({name:'Clamp'});setAttempt(n=>n+1);}return <><h1>Workshop desk</h1><button type="button" onClick={()=>setRecord(null)}>Simulate missing record</button><InspectionBoundary key={attempt} onRetry={retry}><Inspection record={record}/></InspectionBoundary><p>Help desk remains available.</p></>;}The intentional missing-record action causes a descendant render to throw, not the click handler itself. The panel should show its fallback while the heading and help desk remain visible. Retry replaces the bad input and changes the boundary key, creating a fresh boundary and subtree. Changing the key alone while input is still invalid would fail again. Remounting also discards local descendant state, so choose that behavior deliberately. In production report only appropriate sanitized information; the fixture logs a synthetic component stack locally. getDerivedStateFromError must be pure; report in componentDidCatch rather than in render. Browser tests must tolerate development error diagnostics without assuming exact log counts.
Handle event and asynchronous failures at their origin
import React,{useState} from 'react';async function saveInspection(name){if(!name.trim())throw new Error('Name required');return name.trim();}export default function App(){const [name,setName]=useState('');const [message,setMessage]=useState('');const [pending,setPending]=useState(false);async function submit(e){e.preventDefault();setPending(true);try{const saved=await saveInspection(name);setMessage(`Saved ${saved}`);}catch{setMessage('Enter a tool name and retry.');}finally{setPending(false);}}return <form onSubmit={submit}><label>Tool name <input value={name} onChange={e=>setName(e.target.value)} disabled={pending}/></label><button type="submit" disabled={pending}>Save</button><p role="status">{message}</p></form>;}An empty input triggers a rejected promise; the handler catches it and displays a useful message. A valid name produces a success message. Ordinary event-handler errors and asynchronous callback errors are not automatically caught by Error Boundaries. Server-side rendering failures and failures in the boundary itself also need separate handling; an outer boundary may catch a failing inner boundary. React documents special error handling for errors thrown inside a startTransition transition function; do not generalize that to all asynchronous code. A try/catch surrounding JSX creation is not a substitute for a boundary because the child render is scheduled by React later. Expected invalid input should normally be handled without throwing during render.
Reset at a route-like identity boundary
import React,{Component,useState} from 'react';class PanelBoundary extends Component {state={failed:false};static getDerivedStateFromError(){return {failed:true};}render(){return this.state.failed?<p role="alert">Choose another tool to continue.</p>:this.props.children;}}function Detail({id}){const tools={clamp:'Clamp',file:'File'};if(!Object.hasOwn(tools,id))throw new Error('Synthetic missing tool');return <h2>{tools[id]}</h2>;}export default function App(){const [id,setId]=useState('clamp');return <><nav aria-label="Tool views">{['clamp','missing','file'].map(item=><button key={item} type="button" aria-pressed={id===item} onClick={()=>setId(item)}>{item}</button>)}</nav><PanelBoundary key={id}><Detail id={id}/></PanelBoundary></>;}This is a route-like local selection, not a real router integration. Selecting missing shows the fallback; selecting file mounts a fresh boundary and renders File. The navigation remains outside the failing subtree. In a real router choose a route boundary or reset based on a meaningful route identity, preserving unaffected layout state. Router-specific error elements may also handle loader/action errors; use their documented APIs rather than assuming every class boundary catches routing failures. Test keyboard recovery, accessible status announcements and unaffected siblings. Practice: move a failing component inside versus outside the boundary and explain what can recover.