Basic Usage: Executing an effect after every render:
useEffect(() => {
useEffect(() => {
useEffect(() => {
useEffect(() => {
useEffect(() => {
useEffect(() => {
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.
// Perform side effects or subscribe to events
return () => {
// Clean up any resources or subscriptions
};
});
Dependency Array: Controlling when the effect runs by specifying dependencies:
// Perform side effects or subscribe to events
return () => {
// Clean up any resources or subscriptions
};
}, [dependency1, dependency2]);
Run Once (Component Mounting):
// Perform side effects or subscribe to events
return () => {
// Clean up any resources or subscriptions
};
}, []);
Run Once (Component Unmounting):
// 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:
// 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:
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();
}, []);
0 Comments