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!
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
:
