</>
Skip to content
React lessons (30/47)

React — Async

Async/Await

async function fetchData() {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
}

Async in useEffect

function DataComponent() {
    const [data, setData] = useState(null);

    useEffect(() => {
        const loadData = async () => {
            const result = await fetchData();
            setData(result);
        };

        loadData();
    }, []);

    return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}

Async Event Handlers

function LoginForm() {
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);

        try {
            const response = await fetch('/api/login', {
                method: 'POST',
                body: JSON.stringify({ email, password }),
            });

            const data = await response.json();
            console.log('Success:', data);
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <button disabled={loading}>
                {loading ? 'Logging in...' : 'Login'}
            </button>
        </form>
    );
}

Async Examples

// Parallel requests
async function fetchMultipleData() {
    const [users, posts, comments] = await Promise.all([
        fetch('/api/users').then(r => r.json()),
        fetch('/api/posts').then(r => r.json()),
        fetch('/api/comments').then(r => r.json()),
    ]);

    return { users, posts, comments };
}

// Sequential requests
async function fetchSequentialData() {
    const user = await fetch('/api/user/1').then(r => r.json());
    const posts = await fetch(`/api/posts?userId=${user.id}`).then(r => r.json());
    const comments = await Promise.all(
        posts.map(post => fetch(`/api/comments?postId=${post.id}`).then(r => r.json()))
    );

    return { user, posts, comments };
}

// Error handling with retry
async function fetchWithRetry(url, retries = 3) {
    for (let i = 0; i < retries; i++) {
        try {
            const response = await fetch(url);
            if (!response.ok) throw new Error('Request failed');
            return await response.json();
        } catch (error) {
            if (i === retries - 1) throw error;
            await new Promise(resolve => setTimeout(resolve, 1000 * i));
        }
    }
}

// Debounced search
function SearchInput() {
    const [query, setQuery] = useState('');
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        const timer = setTimeout(async () => {
            if (query) {
                setLoading(true);
                const response = await fetch(`/api/search?q=${query}`);
                const data = await response.json();
                setResults(data);
                setLoading(false);
            }
        }, 300);

        return () => clearTimeout(timer);
    }, [query]);

    return (
        <div>
            <input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
            />
            {loading && <p>Loading...</p>}
            <ul>
                {results.map(result => (
                    <li key={result.id}>{result.name}</li>
                ))}
            </ul>
        </div>
    );
}

Mini Practice

Write React code that:

  1. Uses async/await in useEffect
  2. Handles async event handlers
  3. Makes parallel requests
  4. Implements debounced search

Up Next

Next: Learn about Error Handling.

Related Topics

Frequently Asked Questions about Async

What is Async in React?

Async is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Async?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Async.

Why is Async important in React?

Async is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.