HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

React useEffect Hooks

React useEffect Hooks

The useEffect hook in React is used for handling side effects in functional components.

Side effects can include data fetching, subscriptions, manually changing the DOM, and more.

It is a replacement for lifecycle methods such as 'componentDidMount', 'componentDidUpdate', and 'componentWillUnmount' in class components.

Here is a basic example of how to use the 'useEffect hook':

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

function ExampleComponent() {
// State to hold data fetched from an API
const [data, setData] = useState(null);

// useEffect is used for handling side effects
useEffect(() => {
// Code inside here will run after every render
// You can perform asynchronous tasks like data fetching

// Example: Fetch data from an API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(result => setData(result))
.catch(error => console.error(error));

// If you return a cleanup function, it will run before the next effect and on unmount
return () => {
// Cleanup code (unsubscribe, clear intervals, etc.)
};
}, []); // The empty dependency array means this effect runs once after the initial render

return (
<div>
{data ? (
<p>Data: {data} </p>
) : (
<p>Loading... </p>
)}
</div>
);
}

export default ExampleComponent;

In the example above:

  • The 'useEffect' hook takes two arguments: a function containing the code you want to run, and an optional dependency array.
  • The function inside 'useEffect' runs after every render. If you want it to run only once after the initial render, provide an empty dependency array ('[]').
  • The cleanup function returned by 'useEffect' is optional. It runs before the next effect and on component unmount, allowing you to clean up resources or cancel ongoing tasks.