Exploring React's useEffect Hook: Understanding Side Effects and Dependency Arrays
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:
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.
Here, "Component rendered" is logged on every render because useEffect doesn't watch any specific state or props for changes.
