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)
Sharon Matjila
Mpho Oganne
Hophney Lentsoana
1.useEffect is a hook that is used to handle the side effects such as fetching data and updating DOM.
2. We call useEffect a hook because it "hooks into" React's lifecycle features, enabling functional components to perform side effects and manage state, which were previously only possible in class components with lifecycle methods.
3. Initial render: Executes after the initial render of the component.
Example
function MyComponent() { useEffect(() => { console.log('Component rendered!'); // Runs after initial render }, []); // Empty dependency array ensures it runs only once on initial render return (
Dependency change: Runs again if any dependency in the dependency array changes.
example//////
useEffect(() => {
console.log('Dependency changed!');
}, [dependency]);
Cleanup: Returns a function that runs before the component unmounts for cleanup tasks.
example/////
useEffect(() => {
const subscription = fetchData();
return () => subscription.unsubscribe(); // Cleanup function
}, []);