The useEffect hook is a powerful feature in React that allows you to perform side effects in functional components. Here are some common use cases for useEffect:
1. Data Fetching
Fetching data from an API when the component mounts is a
typical use case.
import React, { useEffect, useState } from 'react';
const DataFetchingComponent = () => {
const [data,
setData] = useState([]);
const [loading,
setLoading] = useState(true);
useEffect(() => {
const fetchData
= async () => {
const
response = await fetch('https://api.example.com/data');
const
result = await response.json();
setData(result);
setLoading(false);
};
fetchData();
}, []); // Empty
dependency array means it runs once on mount
<ul>
{data.map(item => (
<li
key={item.id}>{item.name}</li>
))}
</ul>
);
};
2. Event Listeners
Setting up and cleaning up event listeners for actions like
scrolling or resizing.
import React, { useEffect } from 'react';
const WindowResizeListener = () => {
const handleResize
= () => {
console.log('Window
resized!', window.innerWidth);
};
useEffect(() =>
{
window.addEventListener('resize',
handleResize);
return ()
=> {
window.removeEventListener('resize',
handleResize);
};
}, []); // Run
once on mount
return <div>Resize the window and check the console.</div>;
};
3. Timer Functions
Managing timers or intervals, such as updating a clock.
import React, { useEffect, useState } from 'react';
const TimerComponent = () => {
const [time,
setTime] = useState(new Date());
const timerId
= setInterval(() => {
setTime(new
Date());
}, 1000);
}, []);
};
4. Form Handling
Validating form inputs or performing actions based on input
changes.
import React, { useEffect, useState } from 'react';
const FormComponent = () => {
const [inputValue,
setInputValue] = useState('');
const [isValid,
setIsValid] = useState(false);
useEffect(() =>
{
// Simple
validation: check if the input is not empty
setIsValid(inputValue.trim()
!== '');
}, [inputValue]); //
Runs every time inputValue changes
return (
<div>
<input
type="text"
value={inputValue}
onChange={e
=> setInputValue(e.target.value)}
/>
<p>{isValid
? 'Valid input' : 'Input is required'}</p>
</div>
);
};
5. Fetching Data on Dependency Change
Fetching new data when certain dependencies change, such as
a selected user or a filter.
import React, { useEffect, useState } from 'react';
const UserComponent = ({ userId }) => {
const [user,
setUser] = useState(null);
useEffect(() =>
{
const fetchUser
= async () => {
const
response = await fetch(`https://api.example.com/users/${userId}`);
const
result = await response.json();
setUser(result);
};
fetchUser();
}, [userId]); //
Runs when userId changes
if (!user) return <div>Loading
user...</div>;
return <div>{user.name}</div>;
};
Conclusion
These examples illustrate how useEffect can be effectively
used to handle side effects in functional components, including data fetching,
event handling, and managing state based on component lifecycle events.
No comments:
Post a Comment