# react-useDefferredValue

1 min read
Table of Contents

主要作用

我们可以使用useDefferredValue来避免同步渲染造成的页面阻塞

import { useDeferredValue, useState } from 'react'
import { Flex, Input, List } from 'antd'
import mockjs from 'mockjs'
interface Item {
name: string
id: number
address: string
}
function App() {
const [inputValue, setInputValue] = useState('')
const [list] = useState<Item[]>(() => {
return mockjs.mock({
'list|1000': [
{
'id|+1': 1,
name: '@natural',
address: '@county(true)',
},
],
}).list
})
const deferredQuery = useDeferredValue(inputValue)
const isStale = deferredQuery !== inputValue
const findItem = () => {
console.log(deferredQuery, '----', inputValue)
return list.filter((item) => item.name.toString().includes(deferredQuery))
}
return (
<div>
<Flex>
<Input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="请输入姓名"
/>
</Flex>
<List
style={{ opacity: isStale ? 0.5 : 1.0, transition: 'opacity 0.8s ease-in-out' }}
renderItem={(item) => (
<List.Item>
<List.Item.Meta title={item.name} description={item.address} />
</List.Item>
)}
dataSource={findItem()}
/>
</div>
)
}
export default App
My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments