Logo


How can we use IIFE’s in react hooks


We’re are going to learn how we can use IIFE’s (Immediately Invoked Function Expressions) to write asynchronous JavaScript in the useEffect hook.

IIFE’s (Immediately Invoked Function Expressions) are a far lesser-known syntax in JavaScript in my opinion. Basically, an IIFE is a function that is immediately executed after its definition. A lot of you may be wondering now, what is the point. Why even use a function if you are just going to execute it immediately afterward. The answer to that question is quite simple, and that is because we can use async-await syntax inside of it. Below is an example of what an IIFE looks like.


1(async () => {
2  await Foo();
3})();
4

How to use IIFE’s with the useEffect Hook in React

As many developers already know, we cannot use async function in the useEffect hook. Below is the example of code sandbox


1import { useEffect, useState } from "react";
2export default function App() {
3  const [blog, setBlog] = useState([]);
4  useEffect(() => {
5    (async () => {
6      const response = await fetch(
7        "https://jsonplaceholder.typicode.com/posts"
8      );
9      const json = await response.json();
10
11      setBlog(json);
12    })();
13  },[]);
14  return (
15    <ul>
16      {blog.map((post) => (
17        <li key={post.id}>{post.title}</li>
18      ))}
19    </ul>
20  );
21}
22

You will see in the code for our useEffect hook that we are able to use async-await syntax by using an IIFE. That’s really it. It’s that simple. IIFE’s unlock the potential to use async-await syntax inside the useEffect hook.


Here is the link of recoil live example which we done so far:
Click here



About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share