Understanding the useEffect Hook

Understanding the useEffect Hook

Your Guide to React's useEffect Hook

Introduction

In this post, I'm going to tell you about the useEffect hook in React.

I'll explain what it is, how it works, what the dependencies array does, and why cleanup is important.

What is it?

The useEffect hook is a function in React that lets you perform side effects in your component.

Side effects are actions that can affect other components or cannot be done during rendering, such as:

  • Fetching data

  • Directly updating the DOM

  • Setting up subscriptions

How it works

When you use the useEffect hook in a component, it tells React that after rendering, your component needs to do something.

React will then remember the function you passed and call it later after performing the DOM updates.

In this way, useEffect is like a combo of the old lifecycle methodscomponentDidMount, componentDidUpdate, and componentWillUnmount.

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

function App() {
  const [count, setCount] = useState(0); // Initial count 🐣

  // Update the title every time count changes 🌈
  useEffect(() => {
    document.title = `Clicks: ${count} 🐾`;
  });

  return (
    <div>
      <p>Clicks so far: {count} 🎉</p>
      <button onClick={() => setCount(count + 1)}>
        Tap me! 🐾
      </button>
    </div>
  );
}

Dependencies Array

The dependencies array is something you can give to useEffect as a second option to manage when your effect happens.

It's an array of values that, if they change after the page shows again, will make the effect happen again.

// This effect runs only when count changes 🎯
useEffect(() => {
  console.log('Count has changed! 🔄');
}, [count]);

If you pass an empty array ([]), the effect will only run once after the first render.

// This effect runs only once, right after the first render ✨
useEffect(() => {
  console.log('Welcome! First render only 🚀');
}, []);

Cleanup in useEffect (Why and When)

What is Cleanup?

Cleanup in useEffect means stopping or getting rid of actions started by the useEffect hook in React that could affect other parts of your app or system.

These actions could be things such as data subscriptions, timers, or changes to the webpage.

useEffect(() => {
  // Starts a timer that logs after 1 second ⏰
  const timer = setTimeout(() => console.log('Timer done! ⏰'), 1000);

  // Cleanup function to clear the timer 🧹
  return () => {
    clearTimeout(timer); // Stops the timer
    console.log('Cleanup done! 🧹');
  };
}, []); // Runs only once after the first render

Why Cleanup Is Important?

It's key because it stops your app from using too much memory and keeps it running fast.

Imagine your app is like a room where every action from useEffect is like turning on a device.

If you leave these devices on, even when you're not using them, they'll use up energy and make the room cluttered.

Cleanup is like turning off these devices when you leave the room or before you switch them to do something else.

This way, your app doesn't get slowed down by too many things running at once, and it avoids problems that can make the app act weirdly or crash.

When to Cleanup:

You should clean up:

  1. When the Component is Removed:

    This turns off things like data subscriptions or timers that were started by the component. It helps the app run smoothly without using extra memory.

  2. Before Repeating an Action:

    If useEffect reacts to changes, always clean up before it runs again. This stops actions from getting in each others way and keeps the app working properly.

Wrap up

useEffect helps keep your React app running smoothly by managing extra tasks and cleaning them up when necessary.