`useEffect` 在 React 中如何运行清理阶段。

huangapple go评论50阅读模式
英文:

How does `useEffect` run cleanup phase in react

问题

I am trying to implement debounce for searching in Reactjs using useEffect. It works but to be honest I don't really understand how it process.

const [query, setQuery] = useState('')
const [posts, setPosts] = useState([])
useEffect(() => {
    console.log('run useEffect')
    const getData = async () => {
        const { data, status } = await axios.get(`${url}${query}`)
        if (status === 200) setPosts(data.hits)
    }
    const delay = setTimeout(() => {
        console.log('run fetch')
        getData()
    }, 2000)

    return () => {
        console.log('unmounted')
        clearTimeout(delay)
    }
}, [query])

query is the value in the input tag that changes by the onChange event.
When I type a string query, like 'redux', the console order is as follows:

unmounted
run useEffect
unmounted
run useEffect
unmounted
run useEffect
unmounted
run useEffect
unmounted
run useEffect
run fetch

Can I know why it runs the code in the return function first?

英文:

I am trying to implement debounce for searching in Reactjs using useEffect. It works but to be honest I don't really understand how it process

    const [query, setQuery] = useState('')
    const [posts, setPosts] = useState([])
    useEffect(() => {
        console.log('run useEffect')
        const getData = async () => {
            const {data, status} = await axios.get(`${url}${query}`)
            if(status === 200) setPosts(data.hits)
        } 
        const delay = setTimeout(() => {
            console.log('run fetch')
            getData()
        }, 2000)

        return () => {
            console.log('unmounted')
            clearTimeout(delay)
        }
    }, [query])

query is the value in the input tag that change by onChange event.
When I type string query, like 'redux' the order console following:

unmounted
run useEffect
unmounted
run useEffect
unmounted
run useEffect
unmounted
run useEffect
unmounted
run useEffect
run fetch

Can I know why it run the code in the return function first?

答案1

得分: 0

清理逻辑不仅在卸载时运行,而且在每次重新渲染时,依赖项发生变化之前也会运行。

useEffect钩子的deps发生变化时,清理函数将运行。

英文:

See My cleanup logic runs even though my component didn’t unmount

> The cleanup function runs not only during unmount, but before every re-render with changed dependencies.

The clean up function will run when the deps of useEffect hook changes.

huangapple
  • 本文由 发表于 2023年6月15日 15:22:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480052.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定