💻Lecture Notes of Class 10
useEffect Basics
Objective:
- Understand the React component
lifecycle using the useEffect hook.
- Learn how useEffect works on
component mount, update, and cleanup.
- Practice by creating
interactive effects in React components.
1. Introduction to useEffect
React
functional components by themselves do not have lifecycle methods like class
components (e.g., componentDidMount, componentDidUpdate, componentWillUnmount).
To handle side effects (like data fetching, subscriptions, or manually changing
the DOM), React provides the useEffect hook.
What
is a side effect?
- Anything that affects something
outside the scope of the function, such as API calls, event listeners,
timers, or DOM manipulation.
Why use useEffect?
- In class components, you use lifecycle
methods.
- In functional components, useEffect
replaces these lifecycle methods.
- It tells React to perform some
action after rendering.
2. Understanding Component Lifecycle
in React (Simplified)
|
Lifecycle Phase |
What happens? |
useEffect equivalent |
|
Mount |
Component is rendered for first time |
useEffect(() => {...}, []) |
|
Update |
Component re-renders due to state or props change |
useEffect(() => {...}) (without dependencies) or with
specific dependencies |
|
Unmount |
Component is removed from DOM |
Return a cleanup function in useEffect |
3. useEffect on Mount
When
you want to run some code only once when the component first loads
(mounts), you pass an empty dependency array [] as the second argument
to useEffect.
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
alert("Component loaded!"); // runs only once
}, []);
return <div>Hello World</div>;
}
- The empty array [] tells React:
"Only run this effect when the component mounts, not on
updates."
4. useEffect on Update
Sometimes
you want to run an effect every time a certain piece of state or props
changes.
You
do this by passing an array of dependencies to useEffect.
Example:
Update document title when input changes.
import React, { useState, useEffect } from 'react';
function TitleUpdater() {
const [name, setName] = useState('');
useEffect(() => {
document.title = `Hello, ${name}`;
}, [name]); // run effect when `name` changes
return (
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Type your name"
/>
);
}
- Here, useEffect runs only
when the name state changes.
- If name does not change, the
effect is not run again.
5. useEffect Cleanup
Sometimes
effects create subscriptions or timers that need to be cleaned up to avoid
memory leaks.
You
return a cleanup function from inside useEffect. React calls it before the
component unmounts or before running the effect again.
Example:
Timer cleanup
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
const intervalId = setInterval(() => {
setCount(c => c + 1);
}, 1000);
// Cleanup function to clear the timer
return () => clearInterval(intervalId);
}, []); // empty array means run once on mount
return <div>Count: {count}</div>;
}
- Without the cleanup, the timer
would keep running even if the component is removed.
6. Summary Table of useEffect
Behavior
|
useEffect Syntax |
When it Runs |
|
useEffect(() => { ... }); |
After every render (mount + update) |
|
useEffect(() => { ... }, []); |
Only on mount |
|
useEffect(() => { ... }, [dep]); |
On mount and when dep changes |
|
useEffect(() => { return () => {...} }, []); |
On mount, and cleanup on unmount |
7. Activity: Show Alert on Component
Load & Update Title with Input
Part 1: Alert on component load
import React, { useEffect } from 'react';
function AlertOnLoad() {
useEffect(() => {
alert('Component loaded!');
}, []);
return <h1>Welcome!</h1>;
}
Part 2: Update title with input
value
import React, { useState, useEffect } from 'react';
function TitleInput() {
const [text, setText] = useState('');
useEffect(() => {
document.title = text ? `You typed: ${text}` : 'React useEffect Demo';
}, [text]);
return (
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type something..."
/>
);
}
8. Homework Assignment
Create
a clock component that updates every second using useEffect.
Requirements:
- Show current time (hours,
minutes, seconds).
- Update time every second
automatically.
- Use cleanup to clear the timer
on unmount.
9. Additional Notes
- Always add dependencies you use
inside useEffect to the dependency array to avoid stale data bugs.
- If unsure, add all variables
used inside useEffect to dependencies.
- Using empty array ([]) is
useful for running code only once on mount.
10. Q&A and Discussion
- Why do we need cleanup in useEffect?
- What happens if you omit the
dependency array?
- How is useEffect different from
lifecycle methods in class components?
