react effect hook

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.


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.


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.


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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe