Junior — Middle
Can you explain what the useEffect hook in React is used for and what tasks it solves?
sobes.tech AI
Answer from AI
The useEffect hook in React is used for managing side effects in functional components. It allows executing code after the component has rendered, such as fetching data, subscribing to events, or modifying the DOM.
Main tasks of useEffect:
- Performing asynchronous operations (API requests).
- Subscribing and unsubscribing from events.
- Updating state outside React (e.g., interacting with external libraries).
Example of usage:
import React, { useState, useEffect } from 'react';
function Example() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(json => setData(json));
}, []); // Empty array means effect runs once after mounting
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
Thus, useEffect helps manage the component lifecycle and synchronize it with external data sources.