DEV Community

Discussion on: Use Cases for IIFEs

Collapse
 
rampa2510 profile image
RAM PANDEY

I believe one of the most valuable use cases for Immediately Invoked Function Expressions (IIFE) is within the React useEffect hook. In the useEffect hook, you cannot directly run an asynchronous function. Instead, you can declare an asynchronous IIFE and then execute it.

Here's an example in a React component that demonstrates the use of an IIFE in the useEffect hook to fetch data asynchronously:

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

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

  useEffect(() => {
    // Using an async IIFE to fetch data
    (async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    })();
  }, []);

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

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

In this example, the IIFE (async () => { /* ... */ })() is used within the useEffect hook to fetch data asynchronously and update the component's state when the data is received. This pattern allows you to work with asynchronous code in a useEffect hook, where direct use of async functions is not supported.