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:
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:
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.
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
Web developer | React.js | Next.js | Typescript | Node.js | AWS
1 年sources: 1 - https://react.dev