useEffect Hook in React

The useEffect hook allows you to perform side effects in functional components. Side effects are actions that happen "outside" the normal component rendering, such as fetching data, directly updating the DOM, or setting up subscriptions.

1. Basic Syntax

The hook takes two arguments: a callback function and an optional dependency array.

useEffect(() => {
  // Your side effect logic here
  console.log("Component rendered!");
}, [dependencies]);

2. The Dependency Array

The second argument controls when the effect runs:

Value When it runs
undefined (No array)Runs on every render.
[] (Empty array)Runs only once (on mount).
[prop, state]Runs on mount and whenever prop/state changes.

3. The Cleanup Function

Sometimes an effect needs to be "cleaned up" (e.g., stopping a timer or unsubscribing from a chat). To do this, return a function from your useEffect.

useEffect(() => {
  const timer = setInterval(() => { console.log('Tick') }, 1000);

  // Cleanup Function
  return () => clearInterval(timer);
}, []);

Knowledge Check

1. Which dependency array ensures the effect runs only once after the initial render?
A) No array | B) [] | C) [0]

2. What is the primary purpose of useEffect?
A) Storing local state | B) Handling side effects | C) Styling components

3. When does the "cleanup function" run?
A) Before the effect runs again | B) When the component unmounts | C) Both A and B