DEV Community

Ankush Goyal
Ankush Goyal

Posted on

ReactJs: useEffect

The useEffect hook in React is a powerful tool for handling side effects in functional components. Here's a breakdown of how it works and how you can use it effectively:

What is useEffect?

useEffect allows you to perform side effects in your components. Side effects can include data fetching, subscriptions, or manually changing the DOM. It combines the functionality of componentDidMount, componentDidUpdate, and componentWillUnmount from class components.

Basic Usage

The useEffect hook takes two arguments:

  1. A function that contains the side effect logic.
  2. An optional array of dependencies that determine when the effect should run.

Example

Here's a simple example of using useEffect to fetch data:

import React, { useState, useEffect } from 'react';

function DataFetchingComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // Empty array means this effect runs once after the initial render

  return (
    <div>
      {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : 'Loading...'}
    </div>
  );
}

export default DataFetchingComponent;
Enter fullscreen mode Exit fullscreen mode

Dependency Array

The second argument to useEffect is the dependency array. This array determines when the effect should re-run:

  • Empty Array ([]): The effect runs only once, after the initial render.
  • No Array: The effect runs after every render.
  • Specific Dependencies: The effect runs only when the specified dependencies change.

Cleanup

Some effects require cleanup to avoid memory leaks. You can return a cleanup function from the effect:

useEffect(() => {
  const timer = setTimeout(() => {
    console.log('This will run after 1 second');
  }, 1000);

  return () => clearTimeout(timer); // Cleanup the timer
}, []);
Enter fullscreen mode Exit fullscreen mode

Common Use Cases

  • Fetching Data: As shown in the example above.
  • Subscribing to Events: Adding and removing event listeners.
  • Timers: Setting up and clearing intervals or timeouts.

Thank you for reading!
I hope you found this article helpful and informative. If you enjoyed it or learned something new, feel free to share your thoughts in the comments or connect with me.

If you'd like to support my work and help me create more content like this, consider buying me a coffee. Your support means the world and keeps me motivated!

Thanks again for stopping by! 😊

Buy Me A Coffee

Top comments (0)