What is useEffect in React: Explanation and Example
useEffect is a React hook that lets you run code after your component renders, like updating the page or fetching data. It helps you handle side effects in functional components by running code at specific times, such as after the first render or when certain values change.How It Works
Think of useEffect as a way to tell React: "Run this code after you finish updating the screen." It works like a reminder that triggers your code when your component first appears or when some data it depends on changes.
Imagine you just baked cookies and want to tell your friend when they're ready. You set a timer (the effect) that rings after baking (rendering). If you bake again with different ingredients (data changes), the timer resets to notify your friend again. This is how useEffect manages side tasks in React components.
Example
This example shows how useEffect runs code after the component renders and when the count changes.
import React, { useState, useEffect } from 'react'; function Counter() { const [count, setCount] = useState(0); useEffect(() => { document.title = `Count: ${count}`; }, [count]); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } export default Counter;
When to Use
Use useEffect when you need to do things that happen outside the normal rendering process, like:
- Fetching data from a server after the component loads
- Setting up or cleaning up timers or subscriptions
- Updating the document title or interacting with browser APIs
It helps keep your component logic organized and runs side tasks only when needed, improving performance and user experience.
Key Points
useEffectruns after rendering to handle side effects.- You can control when it runs by listing dependencies.
- It replaces lifecycle methods from class components.
- Always clean up effects if they create subscriptions or timers.
Key Takeaways
useEffect runs code after your component renders to handle side effects.useEffect runs by specifying dependencies in an array.useEffect replaces many class component lifecycle methods in functional components.