React - Hooks (useEffect)

React - Hooks (useEffect)

useEffect is a Hook that lets you perform side effects in your components. Side effects are anything that affects something outside of the scope of the current function. For example, fetching data from an API, updating the document title, or setting up a timer are all side effects.

The basic syntax of useEffect

The basic syntax of useEffect is as follows:

useEffect(setup, dependencies);
        

useEffect accepts two arguments: a setup function and an optional array of dependencies. The setup function contains the logic of your side effect. The dependencies array tells React when to run your side effect.

By default, useEffect runs after every render of the component. However, you can control when it runs by specifying the dependencies. If you pass an empty array as the second argument, useEffect will only run once after the initial render. If you pass an array with some values, useEffect will run after the initial render and whenever any of the values in the array change.

An example of useEffect

Let’s see an example of how to use useEffect to fetch some data from an API and display it on the screen. We will use the [JSON Placeholder] API to get some fake posts.

First, we need to import React and useEffect from the “react” module. We also need to import useState, another Hook that lets us manage the state of our component.

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

Next, we need to create a functional component that will render our data. We will call it Posts. Inside the component, we will use useState to create two state variables: posts and loading. posts will store the array of posts that we get from the API, and loading will indicate whether the data is being fetched or not.

function Posts() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(false);
        

Now, we need to use useEffect to fetch the data from the API. We will use the built-in fetch function to make a GET request to the API endpoint. We will also use async/await syntax to handle the asynchronous code.

We will pass an anonymous function as the first argument to useEffect. This function will contain the logic of our side effect. Inside the function, we will do the following steps:

  • Set the loading state to true to indicate that the data is being fetched.
  • Use try/catch blocks to handle any errors that may occur during the fetch operation.
  • Use await to wait for the response from the API.
  • Use await to convert the response to JSON format.
  • Use setPosts to update the posts state with the data from the API.
  • Set the loading state to false to indicate that the data is fetched.

We will pass an empty array as the second argument to useEffect. This means that the effect will only run once after the initial render, and not on every update.

  useEffect(() => {
    async function fetchData() {
      setLoading(true);
      try {
        const response = await fetch("https://jsonplaceholder.typicode.com/posts");
        const data = await response.json();
        setPosts(data);
      } catch (error) {
        console.error(error);
      }
      setLoading(false);
    }
    fetchData();
  }, []);
        

Finally, we need to return some JSX that will display the data on the screen. We will use a conditional rendering to show a loading message while the data is being fetched, and a list of posts when the data is ready.

  return (
    <div className="posts">
      {loading ? (
        <p>Loading...</p>
      ) : (
        <ul>
          {posts.map((post) => (
            <li key={post.id}>
              <h3>{post.title}</h3>
              <p>{post.body}</p>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
        

Why useEffect is useful

You may wonder why we need to use useEffect to perform side effects in our components. Why can’t we just do it inside the component function, or in a lifecycle method if we use a class component?

The answer is that useEffect gives us several benefits over the alternatives. Here are some of them:

  • useEffect helps us separate the concerns of our component. By using useEffect, we can keep the logic of our side effect separate from the logic of rendering our component. This makes our code more readable and maintainable.
  • useEffect helps us avoid bugs and performance issues. By using useEffect, we can avoid unnecessary re-rendering of our component, and prevent memory leaks and stale data. useEffect also ensures that our side effect is cleaned up when the component is unmounted or the dependencies change.
  • useEffect helps us leverage the power of Hooks. By using useEffect, we can access the state and props of our component without using this keyword or passing them as arguments. We can also use other Hooks inside useEffect, such as useRef, useCallback, or custom Hooks.

Conclusion

In this article, we have learned how to use React.js useEffect Hook to perform side effects in our components. We have seen the basic syntax of useEffect, and how to control when it runs by specifying the dependencies. We have also seen an example of how to use useEffect to fetch and display some data from an API. Finally, we have discussed why useEffect is useful and what benefits it gives us.

Sharaf Al Hamza

The full stack developer | learning more about development | I spend the day learning and studying, working on the web at night

1 年

thanks, bro It was very informative information. keep it up

Hassan Fathy

Web developer | React.js | Next.js | Typescript | Node.js | AWS

1 年

sources: 1 - https://react.dev

回复

要查看或添加评论,请登录

Hassan Fathy的更多文章

  • TypeScript - Types vs. Interfaces

    TypeScript - Types vs. Interfaces

    As TypeScript continues to gain popularity among developers for adding type safety to JavaScript, one of the frequent…

  • React - CSS Modules

    React - CSS Modules

    Introduction: In the bustling world of React development, there's a constant quest for more maintainable and scalable…

  • React - Redux Toolkit with TypeScript

    React - Redux Toolkit with TypeScript

    Introduction As a developer, you’ve probably heard about Redux and its powerful state management capabilities. However,…

  • Typescript - Truthiness

    Typescript - Truthiness

    What is truthiness? Truthiness is a term coined by comedian Stephen Colbert to describe something that feels true, even…

  • React - React Router v6

    React - React Router v6

    React Router is a popular library for declarative routing in React web applications. It allows you to define routes as…

  • TypeScript - Equality

    TypeScript - Equality

    TypeScript’s static type checking adds a layer of complexity and safety to equality comparisons, but the JavaScript…

  • React - Hooks(useRef)

    React - Hooks(useRef)

    React's useRef is a hook, a special function that taps into React features in functional components. It returns a…

    2 条评论
  • TypeScript - typeof vs instanceof

    TypeScript - typeof vs instanceof

    Introduction: Unwrap the mysteries of type assertions in TypeScript with two powerful operators: typeof and instanceof.…

  • React - Hooks(useReducer)

    React - Hooks(useReducer)

    Introduction: In the evolving landscape of React, managing state efficiently is critical for crafting responsive and…

  • TypeScript - Type Guards / Narrowing

    TypeScript - Type Guards / Narrowing

    Introduction: In the dynamic world of web development, TypeScript has emerged as an essential tool for building robust…

社区洞察

其他会员也浏览了