- Published on
React & useEffect() Hook
- Authors
- Name
- Kieran Hauser
How React's useEffect() Hook Works
React's useEffect()
hook is a powerful tool that allows developers to manage side effects within functional components. Side effects are any operations that affect the outside world, such as fetching data, modifying the DOM, or updating a server.
The useEffect()
hook allows us to perform these side effects within a functional component, without having to convert it to a class component. The hook takes two arguments: a function that performs the side effect, and an optional array of dependencies that control when the effect is executed.
Here's the syntax for useEffect()
:
useEffect(() => {
// Side effect code goes here
}, [dependency1, dependency2, ...]);
In the above code, the function passed as the first argument is the side effect code. This code will be executed whenever the component is rendered or re-rendered. The second argument is an array of dependencies that control when the effect is executed. If any of the dependencies change, the effect will be executed again.
Now, let's see how we can use useEffect()
to fetch data in a functional component.
Example: Fetching Data Using useEffect()
Suppose we want to build a simple application that displays a list of users fetched from an API. We can represent the state of the application as an array of users and use useEffect()
to fetch the data.
Here's how the code might look:
import React, { useState, useEffect } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => setUsers(data));
}, []);
return (
<div>
<h1>User List</h1>
{users.map(user => (
<div key={user.id}>
{user.name} ({user.email})
</div>
))}
</div>
);
}
In this example, we start with an empty array of users. We use useEffect()
to fetch the data from an API using the fetch()
function. Once the data is fetched, we update the state using setUsers()
. The empty array passed as the second argument to useEffect()
ensures that the effect is only executed once, when the component is mounted.
As you can see, useEffect()
allows us to easily manage side effects in a functional component and build complex UIs with ease. With a little bit of creativity, you can use useEffect()
to build all sorts of interesting applications in React.