Traditional Data Fetching Techniques

Fetch on Render:

Data fetching starts only when component is being rendered on the page.
This is the most widely used data fetching method, usually used with useState to manage loading state.

Key features and concepts:

  1. Data fetching starts after the page is being rendered.
  2. useState is used to manage loading and error state.
  3. Network waterfall is longer than Fetch on Render.

Disadvantages:

  1. Only one fetch call happen at time which severely damages website performance.
  2. Error handling becomes difficult.
  3. Child component’s API call will start only after the completion of parent component.
  4. This method is not SEO friendly.

Example: To demonsrtate using Fetch on Render technique from the component.

Node
import { useState, useEffect } from 'react';
import "./App.css";

function App() {
  const [data, setData] = useState<{ title: string }[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    (async () => {
      setIsLoading(true);
      const resData: { title: string }[] = 
      await fetch("https://jsonplaceholder.typicode.com/todos")
      .then(res => res.json());
      setData(resData);
      setIsLoading(false);
    })()
  }, [])

  return (
    <main>
      {isLoading && <div>Loading...</div>}
      {!isLoading && data.map((item, index) => (
        <div key={index}>
          {item.title}
        </div>
      ))}
    </main>
  );
}

export default App;

Fetch then Render

Data is fetched before rendering the component outside the react component.

Key features and concepts:

  1. Rendering starts after all the data is fetched.
  2. useState is used to manage loading and error state.
  3. Network waterfall is shorter than Fetch on Render.

Disadvantages:

  1. Website performance is impacted as only one API call can occur at a time.
  2. Child component’s API call will start only after the completion of parent component.
  3. Rendering will start after all the data fetching is completed.

Example: To demonsrtate creating a react component which is using Fetch then Render technique.

Node
import { useState, useEffect } from 'react';
import "./App.css";

async function fetchTodo() {
  const data: { title: string }[] = 
  await fetch("https://jsonplaceholder.typicode.com/todos")
  .then(res => res.json());
  return data
}

const allData = fetchTodo();

function App() {
  const [data, setData] = useState<{ title: string }[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    (async () => {
      setIsLoading(true);
      const resData = await allData;
      setData(resData);
      setIsLoading(false);
    })()
  }, [])

  return (
    <main>
      {isLoading && <div>Loading...</div>}
      {!isLoading && data.map((item, index) => (
        <div key={index}>
          {item.title}
        </div>
      ))}
    </main>
  );
}

export default App;

How does Suspense help in Handling Asynchronous Operations in React ?

Suspense, first introduced in React 16, is a feature that aims to enhance the user experience by managing asynchronous operations. It simply lets you render a fallback UI decoratively while the child component is waiting for any asynchronous task to be completed.

Table of Content

  • What is React Suspense?
  • Project Initialisation
  • Traditional Data Fetching Techniques
  • How Suspense works?
  • Use cases of React Suspense
  • Suspense with Server Components in Next.js
  • Conclusion

Prerequisites:

Similar Reads

What is React Suspense?

Suspense allows developers to display a temporary fallback UI when the component is doing the asynchronous operation. When the operation is completed, the actual UI is rendered. Suspense can be used when a child component is lazily loaded or fetching data....

Project Initialisation

Initialise a react project. In this example project, we will use TypeScript, but if you are not comfortable with it, use JavaScript....

Traditional Data Fetching Techniques

Fetch on Render:...

How Suspense works?

React Suspense uses exception control flow. It is related to JavaScript Promise. Regardless, whether if you are using traditional new Promise() or async/await syntax, a JavaScript Promise always has 3 states....

Use cases of React Suspense

1. Revealing nested components while data is loading...

Suspense with Server Components in Next.js

In next.js, we can create a special file called loading.js (or .jsx) for specific route or in root level that automatically wraps page.jsx and other nested routes. We can have small components like spinner, skeleton that are pre-rendered and can be instantly shown while page is loading data. We can define define laoding.jsx in for every route. We can even change the behaviour by defining our own suspense....

Conclusion

In this article, we have explored React Suspense, its benefits, functionality, and practical application through a hands-on React project demonstration. We have covered how Suspense redefines data fetching patterns, addresses loading state challenges, how Suspense works under the hood, and how to use it with React meta-frameworks like Next.js. By mastering Suspense, we have elevated our React development skills and streamlined our application’s performance....