React useEffect Hooks
Pushpendra Tripathi
Software Engineer ??Daily Dev Tips || ?? JS Tricks || Full Stack || 3K+ Followers on Twitter/X ?? || Open for Collaborations ?? || 26K+ LinkedIn Family ?? || AI Enthusiast ?? || YouTuber @UjjwalTechnicalTips ??
In React, the useEffect hook lets you run side effects in your functional components. Side effects can include data fetching, subscriptions, or manually changing the DOM.
useEffect(() => {
// Side effect code here
}, [dependencies]);
Key Points:
useEffect(() => {
const timer = setTimeout(() => {
console.log('Timer triggered');
}, 1000);
return () => clearTimeout(timer); // Cleanup when the component unmounts
}, []);
Example:
import React, { useEffect, useState } from 'react';
function ExampleComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
// Cleanup: Optional return function (for example, to clear an interval)
return () => {
console.log('Cleanup on component unmount or effect re-run');
};
}, [count]); // Only re-run the effect if count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default ExampleComponent;
In this example, the document title updates every time the count value changes.
Example 1: Fetching Data on Component Mount
import { useEffect, useState } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
// Fetch data when the component mounts
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => setData(data));
}, []); // Empty array ensures this effect runs only once
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
Operations Manager .Hospitals Management
5 个月Very useful
Social Media Manager I Influencer I Free Lancer I Personal Branding I Brand Management I LinkedIn Growth #contentcreator #Affiliatemarketing #Facebookbusinessmanager #Digitalmarketingspecialist
5 个月Interesting
Elevating Careers ??| Open for promotion| Excel Expert?? |Helping brands to grow ??
5 个月Great advice
Optimizing LinkedIn Profiles to Attract More Clients & Career Opportunities | Get Your "FREE LinkedIn Profile Audit" Click ???? | Helped 60+ Professionals | Linkedin Personal Branding
5 个月helpful