Skip to main content
useEffect

Share Everywhere

Table of contents

In this tutorial i will discuss about react hook useEffect. If you are a react js developer then it's a very important for you that you have got clear concept about useEffect. This hook seems like componentDidMount(), componentDidUpdate() and componentWillUnmount(). 

Chức năng của useEffect

  • useEffect is a Hook that lets you perform "side effects" in function components, such as data fetching, manual DOM manipulation, and so on...
  • useEffect accepts a function as argument.
  • useEffect runs after every render.

See the below code as an example

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

const MyComponent = ({ }) => {

  const [posts, setPosts] = useState([]);

  useEffect(() => {

    // fetch(`http://localhost:8000/api/expenses/`)

    //  .then(res => res.json())

    //  .then(data => setUser(data));

      async function fetchData() {

        // Call fetch as usual

        const res = await fetch(

          "http://localhost:8000/api/expenses/"

        );

  

        // Pull out the data as usual

        const json = await res.json();

          console.log(json);

          setPosts(json);

        // Save the posts into state

        // (look at the Network tab to see why the path is like this)

        //setPosts(json.data.children.map(c => c.data));

      }  

      fetchData();

  });  

  return (

    <ul>

      {posts.map(post => (

        <li key={post.id}>{post.name}</li>

      ))}

    </ul>

  

  );

}; 

export default MyComponent;

useEffect accepts a second argument: the dependencies array. It tells React to run the effect function only if one of the dependencies as changed. Or you can pass an empty array ([]) to run it only once.

useEffect(() => {
      window.addEventListener("mousedown", eventhandler);

    return () => {
        window.removeEventListener("mousedown", eventhandler);
    };
}, []);
Bạn cảm thấy bài viết này như thế nào?

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
7 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.