useDeferredValue
- In React 18, addressing sluggish rendering is a key goal, and
useDeferredValue
anduseTransition
hooks are introduced for this purpose. - When rendering a component multiple times for a large number of inputs, React’s efficiency can be compromised, leading to delays and slower render times.
useDeferredValue
is a React Hook that postpones updating a portion of the UI. It introduces a delay in updating the hook value, enhancing user experience by preventing immediate rendering and allowing a smoother display of characters as the user types.
Importing:
import { useDeferredValue } from 'react'
Syntax:
const deferredValue = useDeferredValue(value);
Example: below is the practical example of useDeferredValue hook
Javascript
import React, { useState } from 'react' ; import DisplayInput from './DisplayInput' ; function App() { const [userInput, setUserInput] = useState( '' ); const handleInputChange = (e) => { setUserInput(e.target.value); }; return ( <div> <label htmlFor= "userInput" > Enter Text: </label> <input type= "text" id= "userInput" value={userInput} onChange={handleInputChange} /> <DisplayInput input={userInput} /> </div> ); } export default App; |
Javascript
import React, { useDeferredValue } from 'react' ; function DisplayInput({ input }) { const deferredValue = useDeferredValue(input); const renderInputs = () => { const inputs = []; for (let i = 0; i < 20000; i++) { inputs.push( <div key={i}> {deferredValue} </div> ); } return inputs; }; return ( <div> <h2> Displaying {deferredValue} </h2> {renderInputs()} </div> ); } export default DisplayInput; |
Output: There is no delay in updation of input in input box.
New Hooks in React 18
React’s state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState
, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state and lifecycle management in functional components, provide a more versatile approach to React development.
There are several built-in hooks in React, today we are going to see new React hooks that are introduced in React 18.
Table of Content
- useId
- useDeferredValue
- useTransition
- useSyncExternalStore
- useInsertionEffect