I learned about the useEffect Hook in React and created an e-commerce website. I also learned about component lifecycle and dependency arrays.

1. What is useEffect?

useEffect is a React Hook that allows us to synchronize a component with external systems, such as APIs, timers, browser events, and other external resources.

It is commonly used to perform side effects in React components.

Syntax

`import { useEffect } from 'react';

useEffect(() => {
// Side effect code
}, [dependencies]);
`

2. Why do we use useEffect?

  • We use useEffect for tasks such as:
  • Fetching data from an API.
  • Setting up timers.
  • Adding event listeners.
  • Synchronizing with external systems.
  • Cleaning up resources when they are no longer needed.

3. Component Lifecycle

A React component has three commonly discussed lifecycle stages:

Mounting

Mounting happens when a component is created and displayed on the screen for the first time.

Updating

Updating happens when a component renders again because its state or props have changed.

Unmounting

Unmounting happens when a component is removed from the screen.

4. Types of Dependency Arrays in useEffect

There are three common ways to use the dependency array.

1. Empty Dependency Array []

useEffect(() => {
console.log("Component mounted");
}, []);

Runs after the initial render.

Does not run again because of ordinary state or prop updates.

2. Dependency Array with a Value [count]

useEffect(() => {
console.log("Count changed");
}, [count]);

Runs after the initial render.

Runs again whenever count changes.

3. Without a Dependency Array

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

Runs after every render.

4. Cleanup Function

A cleanup function is returned from inside useEffect.

It is useful for cleaning up resources, such as timers and event listeners.

useEffect(() => {
console.log("Effect executed");

return () => { console.log("Cleanup executed"); }; 

}, []);

The cleanup function runs when the component unmounts. When dependencies change, the previous cleanup also runs before the next effect.

What I Learned Today

  • What the useEffect Hook is.
  • Why we use useEffect in React.
  • Component lifecycle: Mounting, Updating, and Unmounting.
  • The three types of dependency arrays.
  • How cleanup functions work.

I also created an e-commerce website as part of my React practice. Every day, I am learning new concepts and improving my understanding of React!