Today’s Offer Enroll today and get access to premium content.
App Store Google Play
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:

  1. Importing: First, import useEffect from React.
  2. Using useEffect: Call useEffect inside your component and provide a function to run your side effect.
  3. 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>; };