React Hooks - useEffect()

phanimurari

Phani Murari

Posted on July 21, 2023

React Hooks - useEffect()

Hey HOOOKERRRR!!!! ๐Ÿ‘‹

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! ๐Ÿš€

Wait, what's useEffect()? ๐Ÿค”

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. ๐Ÿ‘‘

But hold on, here comes the real kicker - useEffect() is for functional components. Now that's pretty neat, huh? ๐Ÿ˜ฒ

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(). ๐Ÿ”ง

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 */]);
Enter fullscreen mode Exit fullscreen mode

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:

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;
Enter fullscreen mode Exit fullscreen mode

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(). ๐Ÿงน

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.

import { useEffect } from 'react';

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

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

  // ...
}
Enter fullscreen mode Exit fullscreen mode

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? ๐Ÿ˜Ž

For a more detailed look at useEffect(), you can always refer to the official React documentation here.

Happy coding! โœŒ๏ธ

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

I'm Phani Murari

Let's connect and keep the learning going ๐Ÿš€

๐Ÿ“ธ Instagram - For behind-the-scenes, daily life and more tech tips.

๐Ÿ’ผ LinkedIn - For professional insights, my latest work updates, and networking opportunities.

Looking forward to meeting you in the digital world! ๐ŸŒ

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
phanimurari
Phani Murari

Posted on July 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

React Hooks - useEffect()
react React Hooks - useEffect()

July 21, 2023

Understanding Common React Hooks
beginners Understanding Common React Hooks

October 15, 2022

First Time with React Hooks
beginners First Time with React Hooks

October 28, 2019

ยฉ TheLazy.dev

About