Skip to content
the poor coder

react effect hook

Poor Man
Published
Reading time
2 min read
On this page

React Effect Hook#

The React Effect Hook is a built-in hook in React that lets you run side effects from a function component. It allows you to perform operations that are not related to rendering or updating the user interface but are still necessary for your application's functionality.

Using the Effect Hook#

The Effect Hook takes two parameters: the first one is a function that contains your side effects, and the second one is an optional array of dependencies. The function will be executed after every render by default, but you can control when it runs by specifying the dependencies.

Text

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

function Example() {
  const [count, setCount] = useState(0);

  // This effect will run after every render
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In the example above, we are using the Effect Hook to update the document title with the current count value every time it changes. Since we didn't specify any dependencies, it will run after every render.

Cleaning Up Effects#

If your side effect creates or modifies something outside of the component, you may need to clean it up when the component unmounts or before it re-renders. To do that, you can return a cleanup function from your effect.

Text

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

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(count + 1);
    }, 1000);

    // Cleanup function
    return () => {
      clearInterval(intervalId);
    };
  }, [count]);

  return (
    <p>{count}</p>
  );
}

In the example above, we are using the Effect Hook to increment the count value every second. We specified the count as a dependency, so it will only run when the count changes. We also returned a cleanup function that clears the interval when the component unmounts or when the count changes.

Multiple Effects#

You can use the Effect Hook multiple times in a component to have different side effects with different dependencies.

Text

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

function Example() {
  const [online, setOnline] = useState(false);
  const [count, setCount] = useState(0);

  useEffect(() => {
    const handleOnline = () => {
      setOnline(true);
    };

    window.addEventListener('online', handleOnline);

    return () => {
      window.removeEventListener('online', handleOnline);
    };
  }, []);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      {online && <p>You are online</p>}
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In the example above, we have two effects: one that listens to the online event and sets the online state to true, and another one that updates the document title with the current count value. The first effect has no dependencies, so it will only run once when the component mounts. The second effect depends on the count value, so it will run after every render when the count changes.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC