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)
Room 8 (Emihle & Nonhlanhla
useEffect is a function provided by the React library, used for handling side effects in functional components. It's a way to run some code after the component has rendered, or when certain dependencies change. Side effects can include things like data fetching, subscriptions, or manually changing the DOM.
When we say that useEffect is a hook, we mean that it's a special function that allows us to "hook into" the lifecycle of a component and execute some code at specific points.useEffect is one such hook, designed to seamlessly integrate with the React rendering process.
useEffect(() => {
return () => {
console.log('Component mounted!');
});
2 We can have the useEffect hook with an empty array, where it will only run once at the beginning, at first render only. e.g
useEffect(() => {
return () => {
console.log('Component unmounted!');
};
}, []);
2.3 If the useEffect has a non-empty array as argument, the hook will run at the start and every time a change is made to the array. e.g
useEffect(() => {
console.log('Count changed to:', count);
}, [count]); (Dependency array includes
count
, so it runs whencount
changes)