React-simple hooks use

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.

 

Published 35 original articles · won praise 1 · views 6718

Guess you like

Origin blog.csdn.net/qq_36162529/article/details/102668047