In this code, the UserList
component is lazy-loaded. The fallback
prop in the Suspense
component displays a loading message until the UserList
component is fully fetched and ready to render.
Creating the Data Fetching Logic
You need to handle the data fetching logic inside the UserList
component. Below is a simple example that fetches user data from an API:
import React, { useEffect, useState } from 'react';
const UserList = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
setUsers(data);
};
fetchData();
}, []);
return (
{users.map(user => (
- {user.name}
))}
);
};
export default UserList;
This component fetches user data from an external API and stores it using the useState
hook. When the data is retrieved, it renders the list of users.
Improving User Experience with Error Boundaries
While React Suspense handles loading states, it's also critical to manage error states. You can use Error Boundaries to catch errors in rendering. Here’s a basic implementation:
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught in Error Boundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return Something went wrong.
;
}
return this.props.children;
}
}
You can implement this ErrorBoundary
in your main component to handle scenarios where errors occur during data fetching or rendering.
Finalizing Your SPA
Now that you have the core components in place, you can build out your SPA further. Consider adding routing functionality using React