Description :
In React, the `useDeferredValue` hook is used to defer the update of a value until the next render cycle.
It is particularly useful when you want to optimize performance by delaying the processing of a value that might change frequently.
The `useDeferredValue` hook takes a value as input and returns a deferred value that can be used in your component.
The deferred value is updated asynchronously during the next render cycle, rather than immediately when the original value changes.
Syntax:
const deferredValue = useDeferredValue(value)
During The Initial Render:
The deferred value will be the same as the value you provided. It starts with the initial value and doesn’t change until the component updates.
During Updates:
The deferred value will “lag behind” the latest value. When an update occurs, React will first re-render the component without updating the deferred value. It keeps using the previous value for the time being. Then, in the background, React attempts to re-render the component again with the newly received value. This second re-rendering is deferred and happens asynchronously, usually when the browser is idle or during low-priority rendering.
import { Suspense, useState, useDeferredValue } from 'react';
import "./App.css";
function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const dummyArray = ['Talib', 'Ajim', 'Salman', 'Zubair', 'Billal', 'Vandit']
return (
<>
<label>
Write Any Characters:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
<Suspense fallback={<h2>Loading...</h2>}>
{
dummyArray.filter((data) => data.toLowerCase().includes(deferredQuery.toLowerCase())).map((data) => <li>{data}</li>)
}
</Suspense>
</>
);
}
export default App;
So In the Above Example, useDeferredValue is used to create a deferred value called deferredQuery based on the query state. The query state is updated when the user types in the input field. By using useDeferredValue, the rendering of the filtered list of names is delayed until the user stops typing. This way, the UI can remain responsive even if there is a delay in filtering the list.
Conclusion :
In conclusion, the `useDeferredValue` hook helps optimize performance, improve user experience, and reduce unnecessary computations or side effects in situations where values change frequently. It gives you more control over the timing of updates and allows React to optimize the rendering process, resulting in a more efficient and responsive application.
Leave a Reply