What are the Different way of using useEffect in React

    Aug 23, 2023       by Pankaj Kumar
useEffect_Hook.png

Certainly! The useEffect hook in React can be used in various ways to handle different scenarios. Here are some common patterns and use cases for using useEffect:

 

Effect with No Dependencies (Runs After Mounting):

If you pass an empty dependencies array ([]) as the second argument to useEffect, the effect will run after the initial render, simulating the behavior of componentDidMount in class components.

 

 
useEffect(() => {
  // This effect runs after the initial render
  console.log("Component mounted!");
}, []);
 

 

2. Effect with Dependencies (Runs on Update):

By passing dependencies to the useEffect, you can control when the effect should run. It will run whenever any of the dependencies change, similar to componentDidUpdate in class components.

 

 
  const [count, setCount] = useState(0);
 
  useEffect(() => {
    // This effect runs whenever 'count' changes
    console.log(`Count is now: ${count}`);
  }, [count]);
 
 

 

3. Cleanup with the Return Function:

You can return a cleanup function from the effect, which will be executed before the next effect or when the component unmounts. This is useful for clearing up resources like subscriptions.

 

 
useEffect(() => {
  const subscription = subscribeToData();
 
  // Cleanup function
  return () => {
    unsubscribeFromData(subscription);
  };
}, [/* dependencies */]);
 

 

4. Effect Without Dependencies (Runs on Every Render):

If you omit the second argument (dependencies array), the effect will run after every render of the component, both on mount and on subsequent updates. This can lead to performance issues if not used carefully.

 

 

 
useEffect(() => {
  // This effect runs after every render
  console.log("Render occurred!");
});

 

5. Running Effects Synchronously after Render:

If you need to perform an effect synchronously after all DOM mutations, you can use useLayoutEffect instead of useEffect.

 

 
import { useLayoutEffect } from 'react';
 
useLayoutEffect(() => {
  // This effect runs synchronously after render
  console.log("DOM mutations complete!");
});
 

 

6. Using Multiple Effects:

You can use multiple instances of useEffect in the same component to separate different concerns into different effects.

 

 
useEffect(() => {
  // Effect for data fetching
  fetchData();
}, [/* data fetching dependencies */]);
 
useEffect(() => {
  // Effect for subscribing to real-time updates
  subscribeToUpdates();
 
  // Cleanup function
  return () => {
    unsubscribeFromUpdates();
  };
}, [/* subscription dependencies */]);
 

 

 

7. Dealing with Asynchronous Effects:

If your effect involves asynchronous operations, you should generally use the cleanup function to handle any necessary cleanups, even if you're using async/await.

 

 
useEffect(() => {
  const fetchData = async () => {
    try {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      setData(data);
    } catch (error) {
      console.error(error);
    }
  };
 
  fetchData();
 
  return () => {
    // Cleanup or cancellation logic if needed
  };
}, []);
 

 

Remember that proper use of useEffect is crucial to avoid bugs and optimize performance. It's important to understand how dependencies work and to manage cleanup operations effectively, especially in complex components with multiple effects.

 

Thanks!


WHAT'S NEW

Find other similar Articles here: