In React 18 there is a new feature called Suspense that lets you declaratively wait for anything including data. Suspense is not a state management system like Redux. It merely enables declarative fallback rendering while a component waits for an asynchronous operation (such as a network request) to be finished. It allows us to synchronize loading states across different components which allows for a better user experience.
How To Use Suspense
Let's compare the implementation of the conventional conditional rendering method against Suspense to see how it works.
import axios from "axios";
import { useEffect, useState } from "react";
const App = () => {
const [isLoaded, setIsLoaded] = useState(false);
const [city,setCity] = useState(null)
const [search,setSearch] = useState("karachi")
useEffect( () => {
axios(`http://api.openweathermap.org/data/2.5/weather?q=${search}&appid=cf7b1a203b58aa52e37fb606f1650331`)
.then((r) => {
console.log(r);
setCity(r.data);
setIsLoaded(true);
})
.catch((e) => {
setIsLoaded(false);
console.log(e);
});
},[search])
return (
<div>
{!isLoaded && <p>loading...</p>}
{isLoaded && (
<input
type="search"
className="inputfield"
onChange={(event) => {
setSearch(event.target.value);
}}
/>
<div>
<h1>
<i className="fas fa-street-view"></i>
{search}
</h1>
<h2>{city.temp}</h2>
<h3>Min : 5.25 cel | Max : 5.25 cel</h3>
</div>
)}
</div>
);
};
export default App;
This method is generally called “fetch-on-render” because fetching doesn’t start until the component has been rendered.
Now let’s see how this example would be rewritten using React Suspense.
import React, { Suspense } from "react";
import "./App.css";
const Weather = React.lazy(() => import("./components/Weather"));
function App() {
return (
<div className="App">
<Suspense fallback={<p>loading...</p>}>
<Weather />
</Suspense>
</div>
);
}
In the code block above, the Weather component is wrapped with a Suspense component which contains a fallback prop. This means that when the component Weather is waiting for an asynchronous operation,React will render "loading..." to the DOM instead.The Weather component is then rendered only after the promises and APIs are resolved.
Top comments (0)