Utilizing UseEffect in React.js

Posted by






UseEffect in React js

UseEffect in React js

React js is a popular JavaScript library for building user interfaces. It provides a feature called useEffect which allows developers to perform side effects in their components. Side effects can include data fetching, subscriptions, changing the DOM, and more.

The useEffect hook is similar to componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class components. It is used to perform actions after the component has rendered, update the component when certain props or state values change, and clean up any resources that the component has created.

Here is an example of how to use useEffect in a React functional component:

    
      import React, { useEffect, useState } from 'react';

      function ExampleComponent() {
        const [data, setData] = useState([]);

        useEffect(() => {
          fetch('https://api.example.com/data')
            .then(response => response.json())
            .then(data => setData(data));
        }, []); // Empty array as the second argument ensures the effect is only run once

        return (
          
{data.map(item => (

{item.name}

))}
); }

In this example, the useEffect hook is used to fetch data from an API when the component is mounted. The empty array passed as the second argument to useEffect ensures that the effect runs only once when the component is mounted. If you want the effect to run whenever a certain value changes, you can pass that value as the second argument to useEffect.

Overall, the useEffect hook is a powerful feature in React js that allows developers to perform side effects in their functional components. It simplifies the process of managing side effects and makes the code more readable and maintainable.