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: Konanani, Samuel, Pumlani
(a) After the initial render: This is the default behavior whenever you use useEffect without an empty dependency array.
import React, { useEffect } from 'react';
Example:
const MyComponent = () => {
useEffect(() => {
console.log('Effect executed after render');
});
return
};
(b) On Mount Only:
import React, { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
console.log('Effect executed on mount');
}, []);
return
};
(c) When Dependencies Change:
import React, { useEffect, useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Effect executed when count changes:', count);
}, [count]);
return (
Count: {count}
<button onClick={() => setCount(count + 1)}>Increment
);
};