Zum Inhalt springen

Understanding useEffect in React: A Beginner’s Guide

Understanding useEffect in React
Introduction
If you’re learning React, you’ve probably come across the useEffect hook and wondered:

“Why do I need it?”

“When does it run?”

“What is it even doing?”

In this blog post, I’ll explain what useEffect is, how it works, and show you examples using a simple React app.

What is useEffect?
useEffect is a React hook that lets you run code after the component renders. It’s used for handling side effects — operations that are not directly related to rendering UI, such as:

Fetching data from an API

Updating the DOM manually

Starting or cleaning up timers

Subscribing to services (e.g., websockets)

Think of useEffect as „do something after the component appears or updates.“

Basic Syntax
jsx
Copy
Edit

import { useEffect } from ‚react‘;

useEffect(() => {
// Your code here (side effect)
}, [dependencies]);
The first argument is a function — the code you want to run.

The second argument is a dependency array — it controls when the effect runs.

Example 1: Logging on Component Mount
jsx
Copy
Edit
import React, { useEffect } from ‚react‘;

function Hello() {
useEffect(() => {
console.log(„Hello component mounted!“);
}, []);

return

Hello, useEffect!

;
}
Explanation:
The console.log runs once when the component mounts.
The empty array [] tells React to run this effect only once, just like componentDidMount in class components.

Example 2: Fetching Data with useEffect
jsx
Copy
Edit

import React, { useState, useEffect } from ‚react‘;

function UserList() {
const [users, setUsers] = useState([]);

useEffect(() => {
fetch(„https://jsonplaceholder.typicode.com/users“)
.then((res) => res.json())
.then((data) => setUsers(data));
}, []);

return (

User List

    {users.map(user => (

  • {user.name}
  • ))}

);
}
Explanation:
This example shows how to fetch and display data using useEffect. The fetch call runs once on component mount and updates the state with the received user data.

Example 3: Cleanup Function
jsx
Copy
Edit

useEffect(() => {
const interval = setInterval(() => {
console.log(„Running interval…“);
}, 1000);

return () => {
clearInterval(interval); // Cleanup on unmount
};
}, []);

Explanation:
The return inside useEffect is a cleanup function. It’s used to clean up side effects when the component unmounts or before the effect runs again.

Conclusion
useEffect is one of the most powerful hooks in React.
You’ll use it for everything from fetching data to handling side effects like timers and subscriptions.

It may seem tricky at first, but once you understand the dependency array and when effects run, it becomes much easier to manage.

Try creating your components using useEffect — it’s a great way to reinforce your learning and grow as a React developer.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert