英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论