💻Lecture Notes Of Class 11
Conditional useEffect and Cleanup
Objective:
- Understand how to control when
effects run in React using useEffect.
- Learn about the dependency
array to conditionally trigger effects.
- Learn about cleanup functions
to prevent memory leaks or unwanted behavior.
1. Introduction to useEffect
- useEffect is a React Hook that
lets you perform side effects in function components.
- Side effects include things
like fetching data from an API, manually changing the DOM, setting up
subscriptions or timers.
- Syntax:
useEffect(() => {
// Effect code here
}, [dependencies]);
2. When does useEffect run?
- By default, useEffect runs after
every render of the component.
- This means every time your
component renders or updates, the effect function runs.
- This can cause performance
issues or unwanted repeated calls if not controlled properly.
3. Controlling useEffect with
Dependency Array
- The second argument of useEffect
is an array called the dependency array.
- This array tells React to only
run the effect if one of the dependencies has changed.
Examples:
- No dependency array:
useEffect(() => {
console.log('Runs after every render');
});
- Empty dependency array:
useEffect(() => {
console.log('Runs only once after the first render');
}, []);
- With dependencies:
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Runs only when count changes:', count);
}, [count]);
- This helps optimize performance
and prevent unnecessary operations.
4. Cleanup in useEffect
- Sometimes, effects create
resources that need to be cleaned up to avoid bugs or memory leaks.
- Examples include:
- Removing event listeners
- Canceling network requests
- Clearing timers
- You can return a cleanup
function from useEffect:
useEffect(() => {
// Setup code here
return () => {
// Cleanup code here
};
}, [dependencies]);
- React calls the cleanup
function:
- Before the component unmounts
- Before running the effect
again (if dependencies change)
5. Practical Example: Fetching a
Joke from an API
Goal:
Create
a React component that fetches a joke from an API and displays it.
Step 1: Set up state for joke and
loading
const [joke, setJoke] = React.useState('');
const [loading, setLoading] = React.useState(true);
Step 2: Fetch joke inside useEffect
(runs only once on mount)
useEffect(() => {
fetch('https://official-joke-api.appspot.com/random_joke')
.then(response => response.json())
.then(data => {
setJoke(data.setup + ' - ' + data.punchline);
setLoading(false);
})
.catch(error => {
setJoke('Failed to fetch joke');
setLoading(false);
});
}, []); // empty array to run only
once
Step 3: Render the joke
return (
<div>
{loading ? <p>Loading...</p> : <p>{joke}</p>}
</div>
);
6. Activity: Add a Button to Fetch a
New Joke
Task:
- Add a button that when clicked
fetches a new joke.
- This means the useEffect should
re-run on button click or you need a function to fetch joke manually.
Solution:
- Add a state fetchTrigger that
changes on button click
- Use fetchTrigger as a
dependency in useEffect
const [fetchTrigger, setFetchTrigger] = React.useState(0);
useEffect(() => {
setLoading(true);
fetch('https://official-joke-api.appspot.com/random_joke')
.then(response => response.json())
.then(data => {
setJoke(data.setup + ' - ' + data.punchline);
setLoading(false);
});
}, [fetchTrigger]);
return (
<div>
{loading ? <p>Loading...</p> : <p>{joke}</p>}
<button onClick={() => setFetchTrigger(prev => prev + 1)}>
Fetch New Joke
</button>
</div>
);
7. Summary
|
Concept |
Explanation |
Example |
|
useEffect |
Runs side effects after rendering |
Fetch data, add event listeners |
|
Dependency Array |
Controls when effect runs |
[] runs once, [count] runs when count changes |
|
Cleanup Function |
Runs before effect re-runs or component unmounts |
Remove event listeners, timers |
8. Homework
- Add a loading spinner or
message that shows while the joke is being fetched.
- Style the button and joke
display nicely.
- Optionally, allow fetching
jokes from different categories (you can research APIs).
Additional Notes for Teacher
- Make sure students understand
the importance of dependencies to avoid infinite loops.
- Explain cleanup with practical
examples (e.g., window event listeners).
- Encourage students to
experiment with changing dependencies and see what happens.
- This topic builds a foundation
for handling side effects properly in React apps.
