Class-32 Reading - Custom Hooks
Reading, Research, and Discussion
1. What does a component’s lifecycle refer to?
- Each React component has a lifecycle that goes through three phases:
- Mounting
- Updating
- Unmounting
These phases can be monitered and the component can be manipulated depending on the phase that it is in.
2. Why do you sometimes need to “wrap” functions in useCallback when called from within useEffect?
- useCallback() allows you to prevent the re-creation of a function while using useEffect (which can be problematic - especially if the function that would be re-created sets off an infinite loop of re-renders)
3. Why are functional components preferred over class components?
- Functional components with the addition of Hooks are able to do the same work that class components are typically responsible for (state, react life cycles, etc) but in a way that is easier to maintain and test, and faster.
4. What is wrong with the following code?
import React, {useState, useEffect} from 'react';
function MyComponent(props) {
const [count, setCount] = useState(0);
function changeCount(e) {
setCount(e.target.value);
}
let renderedItems = []
for (let i = 0; i < count; i++) {
useEffect( () => {
console.log('component mount/update');
}, [count]);
renderedItems.push(<div key={i}>Item</div>);
}
return (<div>
<input type='number' value={count} onChange={changeCount}/>
{renderedItems}
</div>);
}
- useEffect should be on gloable level, not called in a loop.
Vocabulary Terms
state hook
:- def: This is a
useState
hook. It does not merge the old state with the new between re-rendering.- Resource: reactjs.org
- def: This is a
effect hook
:- def: this is a
useEffect
hook. It allows you to perform side effects inside function components.- Resource: reactjs.org
- def: this is a
reducer hook
:- def:
- Resource: reactjs.org
- def: