Understanding the useEffect Hook in React

luhan
Membru
Alăturat:
2024-06-12 06:45:18

Managing side effects such as data fetching, subscriptions, and manually changing the DOM can become challenging when building React applications. React's `useEffect` hook provides a powerful yet straightforward way to handle these side effects in function components. Let’s dive into the basics of `useEffect` to understand how it works and when to use it.

#### What is `useEffect`?

The `useEffect` hook is a function that allows you to perform side effects in function components. It runs after every render by default, making it ideal for operations that need to happen due to state or prop changes, such as fetching data from an API or updating the document title.

Here’s a simple example:

```
import React, { useState, useEffect } from 'react';
const ExampleCode = () => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (

You clicked {count} times




);
}
```

In this example, the document title updates every time the `count` state changes. The `useEffect` hook takes two arguments: a function and a dependency array. The function contains the side effect code, and the dependency array specifies when the effect should re-run. Here, `document.title` is updated whenever `count` changes.

Image preview

luhan
Membru
Alăturat:
2024-06-12 06:48:10

I remember having a very hard time understanding just the basics of `useeffect` but now it is most likely the react hook I use most after `usestate.`

jenny
Membru
Alăturat: 2025-08-24 15:11:06
2024-06-12 07:34:09

When I first learn react, it was class components that I learnt. I was able to easily figure out the onmount having come from oop background. But getting to hooks, I got very confused and stuck with class components until much later. Now I will not even go near class components.

luhan
Membru
Alăturat:
2024-06-12 09:04:47

@"dhtml"#p444 yeahh, class components. I remember taking a course on that one time. I eventually had to stick with functional components

jenny
Membru
Alăturat: 2025-08-24 15:11:06
2024-07-25 12:37:24
[[37],[9]]
Facebook X (Twitter) Instagram LinkedIn Telegram WhatsApp