React Hooks - useEffect()
Tags: react, hooks, beginners, javascript
Published: 2023-07-21 18:12:15


## Hey HOOOKERRRR!!!! :wave:

Today, we're diving into the magical world of React Hooks - focusing specifically on the `useEffect()` Hook. So buckle up and let's get this ride started! :rocket:

## Wait, what's `useEffect()`? :thinking:

Great question! If you're familiar with lifecycle methods in class components like `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`, you can think of `useEffect()` as all these combined into one. Yes, you heard that right! One Hook to rule them all. :crown:

But hold on, here comes the real kicker - `useEffect()` is for functional components. Now that's pretty neat, huh? :astonished:


## Alright, I'm intrigued. But why should I use it? 


Excited about `useEffect()`, but not sure why you'd want to use it? No worries! Let me break it down for you:

- You know when you have to do something extra in your app like getting data from a server, changing something on the screen, or setting up an ongoing process? That's what we call 'side effects', and `useEffect()` is like a magic tool for handling these in functions. 🧰

- Remember how in class components, you might have to write the same code in different lifecycle methods? `useEffect()` helps you avoid this repeat performance by allowing you to put your code in one place only. It's all about that tidy life! 🧹

- Now let's talk about our good friend `useState()`. If you enjoyed how `useState()` made your code shorter and more readable, you're going to love `useEffect()` for the same reasons! It helps to keep your code neat, tidy, and easy on the eyes. 🌈

Feel like a superhero with Hooks yet? Let's fly into more details! 🚀


## Let's get hands-on with `useEffect()`. :wrench:

To use `useEffect()`, you need to call it with a function (which runs your side effect) and an array of dependencies. If any of the dependencies change, the effect will run again.

Here's the basic syntax:

```
useEffect(() => {
    // Your side effect goes here.
}, [/* your dependencies go here */]);
```

**Example**

Let's say we want to fetch a user's data from an API and display it. With `useEffect()`, it's a piece of cake:

```javascript
import { useEffect, useState } from 'react';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch(`https://api.example.com/users/${userId}`)
      .then(response => response.json())
      .then(data => setUser(data));
  }, [userId]); // We're using userId as a dependency

  return (
    <div>
      {user ? (
        <>
          <h1>{user.name}</h1>
          <p>{user.description}</p>
        </>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default UserProfile;
```
In this example, whenever `userId` changes, our effect will run, fetching the new user's data and updating the `user` state. 

## Cleaning up with `useEffect()`. :broom:

Sometimes, your effect might set up something that needs to be cleaned up before the component unmounts, or before the effect runs again. For that, you can return a cleanup function from your effect.

```javascript
import { useEffect } from 'react';

function Timer() {
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      console.log('One second has passed!');
    }, 1000);

    return () => {
      clearTimeout(timeoutId);
    };
  }, []);

  // ...
}
```

In this case, if `Timer` were to unmount before the timeout finishes, the cleanup function would run and prevent the timeout callback from causing an error.

Pretty cool, right? :sunglasses:

For a more detailed look at `useEffect()`, you can always refer to the official React documentation [here](https://reactjs.org/docs/hooks-effect.html). 

Happy coding! :v:

Want to join me on this coding adventure beyond the blog? 

### I'm Phani Murari

Let's connect and keep the learning going  🚀
 
📸 [Instagram](https://www.instagram.com/im_phani_murari/) - For behind-the-scenes, daily life and more tech tips.

💼 [LinkedIn](https://www.linkedin.com/in/phanimurari/) - For professional insights, my latest work updates, and networking opportunities.

Looking forward to meeting you in the digital world! 🌐