CodexBloom - Programming Q&A Platform

React 18: Issues with useTransition and unexpected re-renders when fetching data

👀 Views: 14 💬 Answers: 1 📅 Created: 2025-07-14
react react-transition useTransition JavaScript

Quick question that's been bugging me - I'm working on a project and hit a roadblock. I'm trying to implement concurrent rendering in my React 18 application using the `useTransition` hook to seamlessly load data without blocking the UI... However, I'm encountering unexpected re-renders that are causing my component to flicker. Here’s a simplified version of my code: ```javascript import React, { useState, useTransition } from 'react'; function DataLoader() { const [isPending, startTransition] = useTransition(); const [data, setData] = useState(null); const fetchData = async () => { const response = await fetch('https://api.example.com/data'); const result = await response.json(); setData(result); }; const handleClick = () => { startTransition(() => { fetchData(); }); }; return ( <div> <button onClick={handleClick}>Load Data</button> {isPending ? <p>Loading...</p> : <p>{data ? JSON.stringify(data) : 'No data loaded'}</p>} </div> ); } ``` When I click the button to load the data, the `Loading...` text appears as expected, but after the data is fetched, I also see the component re-rendering unnecessarily multiple times, leading to a flickering effect on the UI. I’ve tried wrapping the `fetchData` function in `startTransition`, but it doesn’t seem to help. I also checked the React DevTools to monitor renders and noticed that the component is re-rendering due to state updates that I hadn't anticipated. Is there something specific about how `useTransition` interacts with state updates that I might be missing? I’m using React 18.0.0, and this behavior wasn’t present when I used `useEffect` for data fetching without transitions. Any insights on how to handle this more efficiently would be greatly appreciated! Has anyone else encountered this? For context: I'm using Javascript on macOS. What's the best practice here? How would you solve this? My development environment is Windows. For context: I'm using Javascript on macOS. Is there a better approach?