Hello friends! 👋
Have you ever built a search feature that feels… laggy? You type into the input, and for a split second, the whole page freezes while it filters a massive list of items.
That is annoying for users. We want our apps to feel snappy, right?
The Problem: Blocking Updates 🛑
In the past, React updates were “all or nothing”. If you told React to update a state, it would stop everything else until that update was finished.
Imagine this scenario:
// A slow component
const HeavyList = ({ query }) => {
// Imagine this filters 10,000 items
const items = filterItems(query);
return (
<ul>
{items.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
);
};
If filterItems takes 500ms to run, your input field will freeze for 500ms every time you type a character. 😱
The Solution: useTransition ✅
React 18 introduced useTransition. This hook allows you to mark some updates as “non-urgent”.
This tells React: “Hey, update the input immediately (urgent), but take your time updating the list (non-urgent).”
Here is how you use it:
import { useState, useTransition } from 'react';
const SearchComponent = () => {
const [isPending, startTransition] = useTransition();
const [input, setInput] = useState("");
const [query, setQuery] = useState("");
const handleChange = (e) => {
// 1. Update the input immediately (Urgent)
setInput(e.target.value);
// 2. Update the query inside a transition (Non-urgent)
startTransition(() => {
setQuery(e.target.value);
});
};
return (
<div>
<input value={input} onChange={handleChange} />
{isPending && <p>Updating list...</p>}
<HeavyList query={query} />
</div>
);
};
How it Works
- Urgent Update:
setInput(e.target.value)happens instantly. The user sees what they typed right away. - Transition:
startTransitionschedules thesetQueryupdate. - Interruptible: If the user types another character while
HeavyListis still rendering, React will pause the rendering, handle the new input, and then restart the rendering with the new value.
This keeps the UI responsive! 🚀
When to use it? 🤔
You do not need useTransition for everything.
- Use it for: Heavy filtering, sorting large lists, or switching between complex tabs.
- Avoid it for: Simple state updates like toggling a modal or small form inputs.
Conclusion
The useTransition hook is a powerful tool in React 18’s concurrent features. It helps you prioritize user interactions over heavy computations.
Give it a try in your next project to make your app feel smoother!
Happy Coding! 🚀