What is the use of useEffect React Hooks?
Sample example code for useEffect() hook to fetch data from an API
import React, { useState, useEffect } from 'react';const UsersList = () => { const [users, setUsers] = useState([]); useEffect(() => { const fetchUsers = async () => { const response = await fetch('https://jsonplaceholder.typicode.com/users'); const data = await response.json(); setUsers(data); }; fetchUsers(); }, []); return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> );};export default UsersList;
import React, { useState, useEffect } from 'react';
const UsersList = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchUsers = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
setUsers(data);
};
fetchUsers();
}, []);
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
export default UsersList;
The useEffect() hook is a built-in hook in React that allows you to perform side effects in functional components. Side effects are anything that affects something outside of the component itself, such as fetching data from an API, modifying the DOM, or subscribing to events.
The useEffect() hook takes two arguments: a function that performs the side effect, and an optional array of dependencies that controls when the side effect should be executed. The function passed to useEffect() will be executed after every render by default, but you can control its execution with the dependency array.
useEffects() runs every time the virtual DOM is rendered. I have mostly used it for initialization of values on the page.