Vishal Yelve
What is the use of useEffect() React Hooks?

What is the use of useEffect React Hooks?

By Vishal Yelve in React on Jan 13 2023
  • Tuhin Paul
    Apr, 2023 15

    Sample example code for useEffect() hook to fetch data from an API

    1. import React, { useState, useEffect } from 'react';
    2. const UsersList = () => {
    3. const [users, setUsers] = useState([]);
    4. useEffect(() => {
    5. const fetchUsers = async () => {
    6. const response = await fetch('https://jsonplaceholder.typicode.com/users');
    7. const data = await response.json();
    8. setUsers(data);
    9. };
    10. fetchUsers();
    11. }, []);
    12. return (
    13. <ul>
    14. {users.map(user => (
    15. <li key={user.id}>{user.name}</li>
    16. ))}
    17. </ul>
    18. );
    19. };
    20. export default UsersList;

    • 0
  • Tuhin Paul
    Apr, 2023 15

    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.

    • 0
  • Munib Butt
    Jan, 2023 26

    useEffects() runs every time the virtual DOM is rendered. I have mostly used it for initialization of values on the page.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS