useEffect is a React Hook used to perform side effects in a functional component.
It is commonly used for:
- Fetching API data.
- Updating the document title.
- Using timers (setTimeout, setInterval).
- Adding event listeners.
Running code when a component loads or when state changes.
useEffect syntax:
import { useEffect } from 'react';
useEffect(() => {
}, []);
- Example: useEffect:
import React, { useState, useEffect } from 'react';
function App() {
const [count, setCount] = useState(0); useEffect(() => { console.log("Component Loaded"); }, []); return ( <div> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)}> Click Me </button> </div> ); }
export default App;
Output:
- When the component loads → Component Loaded
- When you click the button → Count increases.
- The effect does not run again because the dependency array is empty.
- Three types of useEffect:
Type 1: Without dependency array:
useEffect(() => { console.log("Runs after every render"); });
Runs after every render.
Type 2: Empty dependency array :
useEffect(() => { console.log("Runs after initial mount"); }, []);
Runs after the component mounts (in development Strict Mode, React may run an extra setup cycle).
Type 3: With dependency:
useEffect(() => { console.log("Count changed"); }, [count]);
Runs when count changes.
