The goal from this discussion is to solidify your understanding about useEffect after studying about it before the class and in the class.
Please discuss the following questions between you and answer them in the comment section below.
Questions:
- What is
useEffect
? - What do we mean when we say that useEffect is a hook?
- useEffect gets executed in 3 different ways, what are they? (Adding code examples would be beneficial)
Members:
-@Yenkosii
-@Geraldmutsw
-@Letagoeve
1.useEffect is a React hook that allows you to handle side effects in function components. These side effects can involve tasks such as data fetching, setting up subscriptions, or manipulating the DOM directly. By leveraging useEffect, you can make sure your components interact with external systems (like APIs or the DOM) appropriately and efficiently
2.When we say that useEffect is a hook in React, we mean that it's a special function provided by React that allows us to perform side effects in function components
CODE FOR SUBSEQUENT RENDERING
import React, { useState, useEffect } from 'react';
function FetchData() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const fetchedData = await response.json();
setData(fetchedData);
};
}, []); // Empty dependency array for now (replace with relevant dependencies)
return (
{data ? (
Fetched Data: {data.message}
) : (
Loading data...
)}
);
}
export default FetchData;
-Initial Render/Mounting: When a component with useEffect is first displayed on the screen, the code inside the useEffect block runs after this initial render. This behavior is similar to the componentDidMount lifecycle method in class-based React components.
The useEffect hook in
CODE FOR "INITIAL RENDER/MOUNTING
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Component mounted!');
}, []); // Empty dependency array - runs only once after initial render
return (
You clicked {count} times
<button onClick={() => setCount(count + 1)}>Click me
);
}
export default MyComponent;
-Cleanup: The useEffect hook can optionally return a cleanup function. This function runs before the component unmounts (disappears from the screen) or before useEffect itself runs again due to a dependency change. This is useful for cleaning up things like subscriptions or timers to avoid memory leaks or unintended side effects.
CODE FOR CLEAN
import React, { useEffect } from 'react';
function MySubscription() {
useEffect(() => {
const subscription = someEvent.subscribe(() => {
console.log('Event happened!');
});
}, []); // Empty dependency array (adjust if needed)
return (
Subscribed to an event!
);
}
export default MySubscription;