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)
Team Members(Phamela, Siyabonga and Nhlanhla)
Answers.
0. useEffect` is a hook in React that allows you to perform side effects in function components. It's used to execute code that needs to run after the component renders, such as data fetching, subscriptions, or manually changing the DOM.
2- useEffect execution depends on the dependency array you provide:
On Every Render: Leave the dependency array empty ([]):
JavaScript
useEffect(() => {
// Code to run on every render
}, []);
JavaScript
useEffect(() => {
// Code to run only on initial render (similar to componentDidMount)
}, []);
JavaScript
const [count, setCount] = useState(0);
useEffect(() => {
// Code to run on mount and whenever
count
changes}, [count]);