Understanding useEffect
in React can seem challenging. In this article, we'll break down useEffect
in simple words.
What is useEffect?
useEffect
is one of the hooks in React. Let's understand using an imaginary scenario.
Imagine you have a box of delicious cookies and you want to be alerted as soon as someone attempts to steal them.
You can use useEffect
like a magic sensor inside your cookie box. Whenever someone opens the box and takes one out, the sensor notices and sounds an alarm.
But useEffect
sensor can sense multiple things at once.
It can also notice when someone is about to close the lid and which can then make the alarm go off.
And that's it. Congratulations, you now know what useEffect
does! (at a high level)
Why use useEffect?
Imagine you want to fetch data from a website or update the document title. These actions are side effects. They don't directly affect the component's output. That's where useEffect
comes in.
useEffect in React example
Here's a basic useEffect
React example:
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
{data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
In this useEffect React example, we fetch data from a website and display it.