How many ways to use useEffect in react?



In React, the useEffect hook can be used in different ways depending on your specific use case. Here are some common ways to use the useEffect hook in React

Basic Usage: Executing an effect after every render:


useEffect(() => { 
// Perform side effects or subscribe to events 
return () => { 
// Clean up any resources or subscriptions 
}; 
});

Dependency Array: Controlling when the effect runs by specifying dependencies:



useEffect(() => { 
// Perform side effects or subscribe to events 
return () => { 
// Clean up any resources or subscriptions 
}; 
}, [dependency1, dependency2]);

Run Once (Component Mounting):


useEffect(() => {
 // Perform side effects or subscribe to events 
return () => {
 // Clean up any resources or subscriptions
 };
 }, []);

Run Once (Component Unmounting):


useEffect(() => { 
// Perform side effects or subscribe to events 
// Cleanup function only runs on unmount 
return () => {
 // Clean up any resources or subscriptions 
}; 
}, []);

Cleanup Function: Cleaning up after the effect:


useEffect(() => {
 // Perform side effects or subscribe to events
 // Cleanup function runs before re-run or unmount 
return () => {
 // Clean up any resources or subscriptions 
}; });

Async Effects: Using async/await inside the effect:


useEffect(() => { 
const fetchData = async () => { 
try { 
const response = await fetch('https://api.example.com/data');
 const data = await response.json();
// Process the fetched data
 } 
catch (error) {
 // Handle error 
} }; 
fetchData(); 
}, []);


These are just some of the common patterns of using the useEffect hook in React. The useEffect hook provides a flexible and powerful way to handle side effects, subscribe to events, fetch data, and perform cleanup in functional components. The specific usage will depend on your component's requirements and the desired behavior.

Post a Comment

0 Comments