import React, { useState, useEffect } from 'react';
export default function User(){
const [date, setDate] = useState(new Date());
useEffect(() => {
const timeId = setInterval(() => {
setDate(new Date());
}, 1000);
return () => clearInterval(timeId);
})
retrun <div>{date.toLocaleTimeString()}</div>
}
Note: useEffect adds the ability to perform side-effect operations to function components
optimization:
1. Set up dependencies
// Setting an empty array means no dependencies, the side-effect operation is only performed once
useEffect(()=>{...}, [])
useEffect()=>{...}, [fruit])
2. Clearing work:
The return after useEffect can clear some things like timers that need to be cleared.