React useEffect Hook: Side Effects in Functional Components
useEffect is a built-in React hook that allows you to perform side effects in functional components. It's similar to componentDidMount, componentDidUpdate, and componentWillUnmount in class components.
The useEffect hook takes two arguments: a callback function and an optional array of dependencies.
The callback function is executed after every render of the component. It can perform tasks such as fetching data from an API, updating the DOM, or subscribing to events.
The optional array of dependencies determines when the effect should be re-run. If the dependencies array is empty, the effect will only run once after the initial render. If there are dependencies specified, the effect will run whenever any of the dependencies change.
Here's an example of how to use useEffect:
import React, { useEffect, useState } from 'react';
function MyComponent() {
const [data, setData] = useState([]);
useEffect(() => {
// Fetch data from an API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
// Clean up the effect
return () => {
// Unsubscribe from events or cancel async tasks
};
}, []);
return (
<div>
{data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
In this example, the useEffect hook is used to fetch data from an API and update the component's state. The effect runs only once, after the initial render, because the dependencies array is empty. The effect also returns a cleanup function that can be used to unsubscribe from events or cancel any asynchronous tasks when the component unmounts or the effect re-runs.
原文地址: https://www.cveoy.top/t/topic/p4SO 著作权归作者所有。请勿转载和采集!