Học React qua demo về React useEffect Hook dể hiểu
8th Oct 2022In 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); }; }, []);
Add new comment