This site runs best with JavaScript enabled.UseTransition React Hook

UseTransition React Hook


useTransition hook usage example

Instead of updating the state at once, this hooks allows prioritization of what state should be updated first.

A good example would be when user types and expects to see what they've typed, but instead they have to wait for some time if we are rending a very large data after the user types something.

To avoid this useTransition hook comes in handy. We can prioritize updating/rendering of user input, before updating anything else. See example below.

Note: It is advisable to use this hook when necessary because of multiple rendering

1import {Fragment, useState, useTransition} from 'react'
2
3function UseTransitionExample() {
4 const [isPending, startTransition] = useTransition()
5 const [input, setInput] = useState('')
6 const [data, setData] = useState([])
7
8 function handleChange(e) {
9 // high priority
10 setInput(e.target.value)
11 startTransition(() => {
12 // low priority
13 const data = []
14 for (let i = 0; i < 1000; i++) {
15 data.push(e.target.value)
16 }
17 setData(data)
18 })
19 }
20
21 return (
22 <Fragment>
23 <input type="text" value={input} onChange={handleChange} />
24 {isPending
25 ? 'Loading...'
26 : data.map((item, index) => {
27 return <div key={index}> {item} </div>
28 })}
29 </Fragment>
30 )
31}
32
33export default UseTransitionExample
Share article
James Chege

James Chege is a software developer in Nairobi