What is the purpose of the 'useEffect' hook?

Understanding the UseEffect Hook in React

The useEffect hook in React is a powerful tool that allows you to perform side effects in functional components. But what are side effects, and why does React handle them in this way?

Side effects in React are basically anything that affects something outside of the scope of the function being executed. This includes things like data fetching, subscriptions, manual DOM manipulations, timers, logging, and other effects that don't fit into the concept of a "pure" function.

React class components execute the side effects in lifecycle methods, but when you transform those to functional components using hooks, you need a different method, and that's where useEffect comes in.

Here's a basic example of useEffect:

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

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

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

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

In this example, useEffect is called after every render caused by the state change of count. The function passed to useEffect updates the document title once the render is committed to the screen.

Best practices when using useEffect largely revolve around the dependencies array that you pass as the second argument. Omitting this array will cause the effect to run on every render, while an empty array will cause it to only run once on mount, similar to componentDidMount. Be precise with your dependencies to ensure your effects run as needed without causing unnecessary renders.

In conclusion, the useEffect hook in React is used to handle side-effects in functional components. It runs after a render and can be customised to run under specific conditions, making it a powerful and versatile tool in a React developer's toolbox. It replaces lifecycle methods in class-based components, providing a more streamlined and clear way to handle side effects.

Do you find this helpful?