📖 Scenario: You are building a simple React app that fetches user data from an API and displays it. Sometimes the API might fail or return an error. You want to handle these runtime errors gracefully so the app does not crash and shows a friendly message instead.
🎯 Goal: Create a React functional component that fetches user data and handles runtime errors using error boundaries and state. The app should show user names when data loads successfully, and show an error message if something goes wrong.
📋 What You'll Learn
Create a React functional component called UserList.
Use useState to hold user data and error state.
Use useEffect to fetch data from https://jsonplaceholder.typicode.com/users.
Handle fetch errors by setting an error state.
Render user names if data loads, or an error message if there is an error.
💡 Why This Matters
🌍 Real World
Handling runtime errors gracefully is important in real apps to avoid crashes and provide good user experience when things go wrong.
💼 Career
React developers must know how to manage errors and loading states to build robust, user-friendly interfaces.
Progress0 / 4 steps
1
Set up initial state variables
In the UserList component, create two state variables using useState: users initialized to an empty array, and error initialized to null.
React
Hint
Use const [users, setUsers] = useState([]) and const [error, setError] = useState(null) inside the component.
2
Add data fetching with error handling
Inside UserList, use useEffect to fetch data from https://jsonplaceholder.typicode.com/users. If the fetch is successful, update users state with the JSON data. If an error occurs, catch it and update error state with the error message.
React
Hint
Use fetch inside useEffect. Check response.ok and throw an error if false. Use setUsers for data and setError for errors.
3
Render user list or error message
In the UserList component's return statement, render a <ul> with each user's name inside <li> if error is null. If error is not null, render a <p> element with the text Error: followed by the error message.
React
Hint
Use a conditional if (error) to return an error message. Otherwise, map over users to create list items.
4
Add ARIA role and accessibility improvements
Add an aria-live="polite" attribute to the error <p> element to announce error messages to screen readers. Also, add a role="list" attribute to the <ul> element for better accessibility.
React
Hint
Add aria-live="polite" to the error paragraph and role="list" to the unordered list.
Practice
(1/5)
1. What is the main purpose of an error boundary in React?
easy
A. To catch runtime errors in child components and display a fallback UI
B. To improve the performance of React components
C. To handle user input validation
D. To manage component state more efficiently
Solution
Step 1: Understand error boundaries role
Error boundaries catch errors during rendering, lifecycle methods, and constructors of child components.
Step 2: Identify their main use
They prevent the entire app from crashing by showing a fallback UI instead of the broken component.
Final Answer:
To catch runtime errors in child components and display a fallback UI -> Option A
Quick Check:
Error boundaries catch errors = D [OK]
Hint: Error boundaries catch errors and show fallback UI [OK]
Common Mistakes:
Thinking error boundaries improve performance
Confusing error boundaries with input validation
Assuming error boundaries manage state
2. Which of the following is the correct way to define an error boundary component in React?
easy
A. A class component implementing componentDidCatch and getDerivedStateFromError
B. A functional component using useErrorBoundary hook
C. A functional component with try/catch inside render
D. A class component using componentWillCatch lifecycle method
Solution
Step 1: Recall error boundary requirements
Error boundaries must be class components that implement static getDerivedStateFromError and componentDidCatch methods.
Step 2: Check options for correct lifecycle methods
Only A class component implementing componentDidCatch and getDerivedStateFromError correctly names these methods; componentWillCatch does not exist and hooks for error boundaries are not standard.
Final Answer:
A class component implementing componentDidCatch and getDerivedStateFromError -> Option A
Quick Check:
Error boundaries require class + lifecycle methods = A [OK]
Hint: Error boundaries are class components with componentDidCatch [OK]
Common Mistakes:
Using functional components for error boundaries
Using non-existent lifecycle methods
Trying to catch errors inside render with try/catch
3. Given this error boundary component, what will be rendered if a child component throws an error during rendering?