React18 | useTransition hook | Very effective

React18 useTransition hook can improve user experience for example when user start searching something in the search box and UI gets hand because along with typing list also gets filtered.
let copyList = null;const MyComp = (props) => {
let [list2, setList2] = React.useState([]);

React.useEffect(() => {
for(let i = 0; i < 15000; i++) {
setList2((val) => {
return [...val, i];
});
}
}, []);

const handleChange = (event) => {
if (copyList === null) {
copyList = JSON.parse(JSON.stringify(list2));
}
list2 = JSON.parse(JSON.stringify(copyList));

// filtering the list based on the value typed in textbox
if(event.target.value) {
list2 = list2.filter((v) => (v == event.target.value));
}
}

return(
<div>
<input onChange={handleChange} />
{
list2.map((val, key) => {
return (<div key={key}>{val}</div>)
})
}</div>
);
}
const rootElement = document.getElementById("app");
const root = ReactDOM.createRoot(rootElement);
root.render(<MyComp />);
let copyList = null;const MyComp = (props) => {
let [list2, setList2] = React.useState([]);
// using useTransition hook
let [isPending, startTransition] = React.useTransition();

React.useEffect(() => {
for(let i = 0; i < 15000; i++) {
setList2((val) => {
return [...val, i];
});
}
}, []);

const handleChange = (event) => {
if (copyList === null) {
copyList = JSON.parse(JSON.stringify(list2));
}
list2 = JSON.parse(JSON.stringify(copyList));

// filtering the list based on the value typed in textbox by using useTransition hook
startTransition(() => {
if(event.target.value) {
list2 = list2.filter((v) => (v == event.target.value));
}
setList2(list2);
});
}

return(
<div>
{isPending ? 'Wait searching...' : ''}
<input onChange={handleChange} />
{
list2.map((val, key) => {
return (<div key={key}>{val}</div>)
})
}</div>
);
}
const rootElement = document.getElementById("app");
const root = ReactDOM.createRoot(rootElement);
root.render(<MyComp />);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store