Intermediate
What is the purpose of the useEffect hook in React?
The useEffect
hook is a fundamental part of React functional components that allows you to perform side effects in your components, such as data fetching, subscriptions, or manually changing the DOM.
Here’s how it works:
- Importing: First, import
useEffect
from React. - Using useEffect: Call
useEffect
inside your component and provide a function to run your side effect. - Dependency Array: Optionally, pass a dependency array to control when the effect runs.
Example:
import React, { useEffect, useState } from 'react'; const MyComponent = () => { const [data, setData] = useState([]); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); return <div>{data.map(item => <p key={item.id}>{item.name}</p>)}</div>; };