Async/Await vs Callbacks in React

Converting your Callback Functions into Async/Await Functions in under 3 minutes! (React 16): Callback functions can start to look like hell. Here is a quick way to do it using the async/await syntax.

Callback functions can start to look like hell. Here is a quick way to do it using the async/await syntax.

Table of Contents

I created a video on my channel: “Coding with Lewis”.

Converting Callbacks to Async/Await

When you’re working with React and dealing with asynchronous operations, callback functions can quickly become nested and difficult to read. This is often called “callback hell.”

Here’s how you can convert your callback-based code to use the much cleaner async/await syntax:

Before: Using Callbacks

function fetchData(callback) {
  setTimeout(() => {
    callback(null, 'Data fetched successfully');
  }, 1000);
}

function handleData() {
  fetchData((error, data) => {
    if (error) {
      console.error('Error:', error);
    } else {
      console.log('Success:', data);
      // More nested callbacks here...
    }
  });
}

After: Using Async/Await

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data fetched successfully');
    }, 1000);
  });
}

async function handleData() {
  try {
    const data = await fetchData();
    console.log('Success:', data);
    // Clean, readable code
  } catch (error) {
    console.error('Error:', error);
  }
}

Why Async/Await is Better

  1. Readability: Code reads more like synchronous code
  2. Error Handling: Try/catch blocks are more intuitive
  3. Debugging: Easier to debug with better stack traces
  4. Maintainability: Less nesting means easier maintenance

React Example

Here’s how this applies in a React component:

import React, { useState, useEffect } from 'react';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchUser() {
      try {
        setLoading(true);
        const response = await fetch(`/api/users/${userId}`);
        const userData = await response.json();
        setUser(userData);
      } catch (error) {
        console.error('Failed to fetch user:', error);
      } finally {
        setLoading(false);
      }
    }

    fetchUser();
  }, [userId]);

  if (loading) return <div>Loading...</div>;
  if (!user) return <div>User not found</div>;

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  );
}

This approach makes your React components much cleaner and easier to understand!

Thanks for stopping by :)

Subscribe to our newsletter

Our magazine

Read our blog
I Fixed My ADHD with a Receipt Printer - The Story Behind the Viral Project

I Fixed My ADHD with a Receipt Printer - The Story Behind the Viral Project

How a simple receipt printer became my ultimate productivity tool and spawned a viral GitHub project that resonated with developers worldwide.

Reddit has changed. Why I miss the old Reddit.

Reddit has changed. Why I miss the old Reddit.

The new Reddit has me constantly feeling nostalgic over the old Reddit. Why I miss the easier times.

Building a Python Meme Generator - When Code Meets Comedy

Building a Python Meme Generator - When Code Meets Comedy

How I built an automated meme generator in Python that creates viral-ready content from templates and proves that programming can be fun.

How I Built a Bot with 8.3K GitHub Stars - RedditVideoMakerBot

How I Built a Bot with 8.3K GitHub Stars - RedditVideoMakerBot

The story behind RedditVideoMakerBot - my most popular open-source project that automates Reddit video creation with just one command.