This is the 29th day of my participation in the August More Text Challenge
What is a useEffect?
Give functional components the ability to handle side effects, similar to life cycle functions.
1. UseEffect Execution time
Can consider useEffect componentDidMount componentDidUpdate, componentWillUnmount that the combination of the three functions.
- When componentDidMount and componentDidUpdate
function App() {
const [count,setCount] = useState(0);
// Execute after component is mounted or component data is updated
useEffect(() = > {
console.log('Execute after component is mounted or component data is updated');
})
return (
<div>
{count}
<button onClick={()= > setCount(count + 1)}>+1</button>
</div>)}Copy the code
- Only when comonentDidMount
useEffect(() = > {
console.log('Only as componentDidMount'); }, [])Copy the code
- When used as componentWillunmount (note: not only as componentWillunmount)
useEffect(() = > () = > {
console.log('as componentWillUnmount');
})
Copy the code
2. Example of using useEffect
- Add a scroll event to the window object. (Bind events after mounting and unbind components after unmounting)
function App() {
function onScroll() {
console.log('I'm listening for page scrolling');
}
useEffect(() = > {
window.addEventListener('scroll',onScroll);
return () = > {
// Unbind events when uninstalling components
window.removeEventListener('scroll',onScroll); }})return (
<div>
App
</div>)}Copy the code
- Set the timer so that count increases by 1 every second.
function App() {
const [count,setCount] = useState(0);
useEffect(() = > {
const timeId = setInterval(() = > {
setCount(count= > count + 1);
},1000)
return () = > {
clearInterval(timeId);
}
},[])
return (
<div>
<h1>The current sum is: {count}</h1>
</div>)}Copy the code
3. UseEffect solved problems
- Put a coherent set of business logic into the same side effect function.
- Simplify repetitive code and make the internal code of components clearer.
4: The second parameter of useEffect
- An effect is triggered only when specified data changes
useEffect(() = > {
document.title = count;
}, [count])
Copy the code
5: useEffect combines asynchronous functions
Using async and await directly in useEffect is an error and it is recommended to wrap asynchronous functions with immediate execution functions.
function getData() {
return new Promise(resolve= > {
resolve({msg: 'Hello'})})}function App() {
useEffect(() = >{(async function () {
const result = await getData();
console.log(result); }}) (), [])return (
<div>
App
</div>)}Copy the code
reference
- The official documentation