How to Work useEffect?
`useEffect` is a hook in React that allows you to perform side effects in functional components. Side effects can include things like fetching data, updating the DOM, setting up event listeners, or any other operation that needs to be performed after rendering.
The `useEffect` hook takes two parameters: a function that contains the side effect, and an optional array of dependencies. The function is executed after every render of the component, and the dependencies are used to determine when the effect should be re-run.
Here's an example of using the `useEffect` hook to fetch data from an API when a component mounts:
import React, { useState, useEffect } from 'react';
function MyComponent() {
?const [data, setData] = useState([]);
?useEffect(() => {
??async function fetchData() {
???const response = await fetch('https://my-api.com/data');
???const data = await response.json();
???setData(data);
??}
??fetchData();
?}, []);
?return (
??<div>
???{data.map(item => (
????<p key={item.id}>{item.name}</p>
???))}
??</div>
?);
}
领英推荐
In this example, the `useEffect` hook runs the `fetchData` function after the component mounts. Since an empty dependency array is passed as the second argument to `useEffect`, this effect only runs once when the component first mounts. If the dependency array contained a value that changes, the effect would re-run every time that value changes.
`useEffect` also returns a cleanup function that can be used to clean up any resources or event listeners created by the effect. For example, you can use `useEffect` to set up an event listener and clean it up when the component unmounts:
import React, { useEffect } from 'react';
function MyComponent() {
?useEffect(() => {
??function handleClick() {
???console.log('Button clicked');
??}
??const button = document.querySelector('#my-button');
??button.addEventListener('click', handleClick);
??return () => {
???button.removeEventListener('click', handleClick);
??};
?}, []);
?return <button id="my-button">Click me</button>;
}
In this example, the `useEffect` hook sets up a click event listener on the button, and returns a cleanup function that removes the listener when the component unmounts.