Introduction

Welcome! Today, we'll traverse React's cosmos, exploring the useEffect Hook. We'll delve into the basics of useEffect, unravel the concept of side effects, and decipher the dependency array. Additionally, we'll understand how useEffect behaves in three scenarios: when it has no dependency array, an empty array, and a non-empty array. Are you ready? Let's begin!

Introduction to `useEffect`

First, let's demystify useEffect. It's a React Hook that introduces effects to functional components. "Effects" encapsulate the actions or tasks that occur as a component renders, updates, or unmounts. But before we proceed, we should briefly revisit the useState Hook; useState provides a "state"—think of it as short-term memory—for functional components.

Consider a simple web application that displays a counter, incrementing each time the user clicks a button. In addition to counting clicks, we want to log a console message each time the counter updates. To accomplish this, we utilize useEffect:

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

function CounterApp() {
  // useState is used to add a counter state to our component
  // setCounter is a function to update the current counter
  const [counter, setCounter] = useState(0);
  
  useEffect(() => {
    // useEffect logs the current counter value each time it changes
    console.log(`Counter value: ${counter}`);
  }, [counter]); // observe changes in the counter

  return (
    <div>
      <p>Counter: {counter}</p>
      <button onClick={() => setCounter(counter + 1)}>
        Increase Count
      </button>
    </div>
  );
}
export default CounterApp;
Understanding the Dependency Array

The dependency array, which is the second argument of useEffect, informs useEffect which states or props should be watched. useEffect re-runs whenever these watched entities change.

`useEffect` with No Dependency Array

What happens when useEffect lacks a dependency array? It runs after every render, regardless of which changes triggered the render.

useEffect(() => {
  console.log(`Component rendered.`);
});

Here, "Component rendered" is logged on every render because useEffect doesn't watch any specific state or props for changes.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal