Welcome back to CodeYourCraft! Today, we're going to dive into an essential concept of React JS: Fallback UI.
In React, Fallback UI, or fallback components, are used to provide a placeholder or default UI while data is being fetched or during asynchronous operations. This helps to improve the user experience by ensuring that the UI remains responsive and informative, even when data is not immediately available.
Let's create a simple fallback UI for a component that fetches data from an API.
import React, { useState, Suspense } from 'react';
import axios from 'axios';
const MyComponent = React.lazy(() =>
import('./MyComponent').then(({ default: MyComponent }) => ({
default: MyComponent,
}))
);
function App() {
const [data, setData] = useState(null);
const fetchData = async () => {
const response = await axios.get('https://api.example.com/data');
setData(response.data);
};
useEffect(() => {
fetchData();
}, []);
return (
<div>
<button onClick={fetchData}>Fetch Data</button>
{data ? <MyComponent data={data} /> : <p>Loading data...</p>}
<Suspense fallback={<p>Oops, something went wrong!</p>}>
<MyComponent data={data} />
</Suspense>
</div>
);
}
export default App;In this example, we're using React's Suspense component to wrap our data-fetching component (MyComponent). If the component is still loading or an error occurs, the fallback UI will be displayed. The fallback UI in this case is a simple message that indicates the data is being loaded or something went wrong.
What is the purpose of Fallback UI in React?
We hope you enjoyed learning about Fallback UI in React. Stay tuned for more exciting tutorials here at CodeYourCraft! 🚀