useTransition
useTransition
addresses performance concerns in React applications by enhancing UI responsiveness, ensuring a smoother user experience even during background processing.- In scenarios like a search component with dynamic filtering, where multiple states are updated simultaneously (e.g., search input and filtered results), React’s default high-priority updates can lead to potential slowdowns.
- The issue arises when managing numerous user inputs, causing delays in updating states and impacting user interaction.
useTransition
resolves this by allowing low-priority state updates through the startTransition function, preventing UI blocking and optimizing overall performance.
Import:
import { useTransition } from 'react'
Syntax:
const [isPending, startTransition] = useTransition()
Example: below is the practical example of useTransition hook
Javascript
import React from 'react' ; import SearchList from './SearchList' ; function App() { return ( <div> <SearchList /> </div> ); } export default App; |
Javascript
import React, { useState, useTransition } from 'react' ; const namesList = [ 'Alice' , 'Bob' , 'Charlie' , 'David' , 'Eva' , 'Frank' // ... Add more names as needed ]; function SearchList() { const [searchTerm, setSearchTerm] = useState( '' ); const [filteredNames, setFilteredNames] = useState(namesList); const [isPending, setTransition] = useState(); const handleSearch = (e) => { const term = e.target.value.toLowerCase(); setSearchTerm(term); setTransition(() => { const filtered = namesList.filter( name => name.toLowerCase() .includes(term) ); setFilteredNames(filtered); }) }; return ( <div> <label htmlFor= "search" > Search: </label> <input type= "text" id= "search" value={searchTerm} onChange={handleSearch} placeholder= "Type to search names" /> <ul> { filteredNames.map((name, index) => ( <li key={index}> {name} </li> )) } </ul> </div> ); } export default SearchList; |
Output:
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