Use async/await in React useEffect

Let's assume that you want to use an async function in a useEffect Hook in React:

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

const App = () => {
    
    const [status, setStatus] = useState(null);
    
    useEffect(() => {
        
        // You can't use useEffect(async () => await function(), []);
        // You should define the function instead and call it directly
        const getStatus = async () => {
            
            let response = await fetch('https://erikmartinjordan.com');
            
            setStatus(response.status);
            
        }
        
        getStatus();
        
        
    }, []);
    
    return(<div>{status}</div>);
    
}

export default App;

You can use an Immediately Invoked Function Expression (IIFE) as well:

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

const App = () => {
    
    const [status, setStatus] = useState(null);
    
    useEffect(() => {
        
        // In React you can't use useEffect(async () => await function(), []);
        // Define the function instead and call it directly
        (async () => {
            
            let response = await fetch('https://erikmartinjordan.com');
            
            setStatus(response.status);
            
        })();
        
        
    }, []);
    
    return(<div>{status}</div>);
    
}

export default App;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.