Day 2 of Mastering React Hooks – Diving Deep into useEffect ???
Kshitish Kumar Pothal
Next Js || React js || Frontend Developer || Wix || DSA || 500+ DSA Problem Solved || Java || Python || Kotlin || AWS
Introduction to useEffect
Welcome to Day 2 of mastering React hooks! Today’s spotlight is on useEffect, the cornerstone of handling side effects in React functional components. If useState manages state, useEffect manages behavior that happens outside the component, such as data fetching, subscriptions, timers, and DOM updates.
What is useEffect?
The useEffect hook allows you to perform side effects in your components. It’s the functional equivalent of lifecycle methods in class components like componentDidMount, componentDidUpdate, and componentWillUnmount.
Key Features:
How useEffect Works
The syntax is simple yet powerful:
useEffect(() => {
// Perform side effects here
return () => {
// Cleanup logic (optional)
};
}, [dependencies]);
Key Elements:
Modes of useEffect
useEffect(() => {
console.log('Runs on every render');
});
useEffect(() => {
console.log('Runs once when the component mounts');
}, []);
useEffect(() => {
console.log(`Count updated to: ${count}`);
}, [count]);
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => {
clearInterval(timer); // Cleanup on unmount or dependency change
};
}, []);
Common Use Cases
Fetch data from APIs when the component mounts:
领英推荐
useEffect(() => {
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
}
fetchData();
}, []);
Dynamically update the document title:
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
Add and clean up event listeners:
useEffect(() => {
const handleResize = () => console.log('Window resized');
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize); // Cleanup
}, []);
Subscribe to a service and unsubscribe on cleanup:
useEffect(() => {
const subscription = someService.subscribe(data => setData(data));
return () => subscription.unsubscribe();
}, []);
Tips for Mastering useEffect
Avoid writing large or unrelated logic in a single useEffect. Split effects if necessary.
useEffect(() => {
// Effect A
}, [depA]);
useEffect(() => {
// Effect B
}, [depB]);
Understand how dependencies impact when the effect runs. If your effect doesn’t rely on any external value, use an empty array ([ ]).
Add meaningful console logs or use tools like React DevTools to inspect how and when your effects execute.
Be cautious when setting state inside an effect. If the state update triggers the effect, you might create a loop.
Why useEffect Matters
The useEffect hook is foundational for building dynamic, interactive React applications. It bridges the gap between your component and the outside world, enabling real-time interactions, external data fetching, and resource management.
Mastering useEffect is a step toward writing efficient and maintainable React applications. Take it one step at a time—experiment with simple use cases, and soon, it’ll become second nature.
Happy coding! ??