- The useEffect hook in React allows you to perform side effects, such as fetching data from an API or updating the document title, after rendering a component. It takes a function as its first argument that will be executed after each render. However, sometimes you may also want to clean up any resources used by that function or cancel any pending requests when the component is unmounted or updated. For this purpose, you can specify a cleanup function as the second argument of useEffect.
- The cleanup function is a function that will be executed when the component is unmounted or updated. The cleanup function is specified as the return value of the first function passed to useEffect.
useEffect(() => {
// effect code here
return () => {
// cleanup code here
};
}, [/* dependency array */]);
- In this example, the first argument of useEffect is a function that performs some effect. The second argument is an array of dependencies. If any of the dependencies change between renders, the effect function will be re-run.
- The second argument of useEffect is a cleanup function that will be executed when the component is unmounted or updated. This function should clean up any resources used by the effect function or cancel any pending requests. It is typically used to clean up event listeners, timers, or subscriptions.
useEffect(() => {
const handleClick = () => {
// handle click event
};
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
}, []);
- In this example, the effect function adds an event listener to the document object that listens for click events. The cleanup function removes the event listener to prevent memory leaks.
- It's important to note that the cleanup function is not executed on the first render. It's only executed when the component is unmounted or updated. If you need to execute some code when the component is mounted, you can do that directly in the effect function.
No comments:
Post a Comment