This site runs best with JavaScript enabled.UseDeferredValue Hook

UseDeferredValue Hook

Photo by scott tribby


UseDeferredValue Hook usage example

useDeferredValue stores a copy of the previous value and only gets updated after the user has stopped typing.

This hook helps throttle expensive re-renders

React 18 is smart enough to know when to update the value without having to explicitly specify the time to update the stored value

See the example below

1import {Fragment, useDeferredValue, useMemo, useState} from 'react'
2
3function Example() {
4 const [input, setInput] = useState('')
5
6 function handleChange(e) {
7 setInput(e.target.value)
8 }
9
10 return (
11 <Fragment>
12 <input type="text" value={input} onChange={handleChange} />
13 <List input={input}></List>
14 </Fragment>
15 )
16}
17
18const List = ({input}) => {
19 const deferredInput = useDeferredValue(input)
20
21 return useMemo(() => {
22 const values = []
23 for (let i = 0; i < 10000; i++) {
24 values.push(<p key={i}>{input}</p>)
25 }
26 return values
27 }, [deferredInput])
28}
Share article
James Chege

James Chege is a software developer in Nairobi