Detailed explanation of useEffect in react-Hook (use useEffect to clear the timer)

useEffect

Before we learned the declaration cycle of class components, can we do some operations related to the declaration cycle in functional components?
There is no lifecycle in functional components, so useEffect can be used instead. We can think of useEffect as a combination of three lifecycle methods of component loading, component updating, and component unloading.

Let's learn the use of useEffect through a case:
1. The requirement here is to write a click event to accumulate the state, and display the state on the title
2. First import React, { useState, useEffect }
3. Then use useEffect to convert the state Render to title
4. Finally bind the click event

import React, {
    
     useState, useEffect } from 'react'

export default function App() {
    
    
    const [state, setstate] = useState(0)

    useEffect(() => {
    
    
        document.title = `你点击了${
      
      state}次`
    })
    return (
        <div>
            <h1>{
    
    state}</h1>
            <button onClick={
    
    e => setstate(state + 1)}>点击</button>
        </div>
    )
}

Check the running effect:
insert image description here
so we can find:By default useEffect will be executed after the first render and before every update

Based on this feature, let's look at another example:
1. The effect achieved is that clicking the button can switch the state whether to display the page page or not. The button on the page page can control the changes of age and money. It is relatively simple and everyone should be able to understand it.

import React, {
    
     useState, useEffect } from 'react'

function Page() {
    
    
    const [age, setage] = useState(18)
    const [money, setmoney] = useState(1000)

    useEffect(() => {
    
    
        console.log('我被执行了')
    })
    return (
        <div>
            <h1>{
    
    age}</h1>
            <h2>{
    
    money}</h2>
            <button onClick={
    
    e => setage(age + 1)}>长大</button>
            <button onClick={
    
    e => setmoney(money + 1000)}>变有钱</button>
        </div>
    )
}

export default function App() {
    
    
    const [show, setshow] = useState(true)
    return (
        <div>
            <h1>{
    
    show}</h1>
            <button onClick={
    
    e => setshow(!show)}>切换状态</button>
            {
    
    show && <Page/>}
        </div>
    )
}

I have printed in useEffect here. Let's see when useEffect is triggered.
insert image description here
You can see that useEffect is triggered every time it is updated. UseEffect here can also pass in parameters, for example:
write age in the following array And money, the effect is the same

useEffect(() => {
    
    
        console.log('我被执行了')
    }, [age, money])

But if you just write one:

useEffect(() => {
    
    
        console.log('我被执行了')
    }, [age])

View the result:
insert image description here
you can see that it will be called when the age state changes, but when the money changes, it will not be called
So here the array is passed in as a dependency. Only when the state in the array changes will it trigger the useEffect execution.

If we want to make a request in useEffect, that is, we only want it to fire once, what should we do:
use an empty array as follows:

useEffect(() => {
    
    
        console.log('我被执行了')
    }, [])

useEffect clears the timer

Let's first review how to clear the timer in the class component:
For example, the following code needs to clear the timer in the componentWillUnmount life cycle function

export class App extends Component {
    
    
    state = {
    
    
        count: 0
    }
    componentDidMount() {
    
    
        this.timer = setInterval(() => {
    
    
            this.setState({
    
    count: this.state.count + 1})
        }, 500)
    }
    componentWillUnmount() {
    
    
        clearInterval(this.timer)
    }
    render() {
    
    
        return (
            <div>
                <h1>{
    
    this.state.count}</h1>
            </div>
        )
    }
}

So how to use useEffect to achieve it?
Just return it out, look at the following code

import React, {
    
     useState, useEffect } from 'react'

export default function App() {
    
    
    const [state, setstate] = useState(0)
    useEffect(() => {
    
    
        const timer = setInterval(() => {
    
    
            setstate(prev => prev + 1)
        }, 1000)
        // 清除定时器
        return () => clearInterval(timer)
    }, [])
    return (
        <div>{
    
    state}</div>
    )
}

At last

The explanation of this article is here. It mainly introduces the function and usage of useEffect, as well as how to use it to clear the timer. If it is helpful to you, please like, follow and support~ I will bring you more in the future. Multiple premium content

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123601788
Recommended