DEV Community

Cover image for 𝗚𝗼𝗼𝗱𝗯𝘆𝗲 𝘂𝘀𝗲𝗦𝘁𝗮𝘁𝗲 𝗳𝗼𝗿 𝗟𝗼𝗮𝗱𝗶𝗻𝗴 𝗦𝗽𝗶𝗻𝗻𝗲𝗿𝘀: 𝗛𝗼𝘄 𝘂𝘀𝗲𝗧𝗿𝗮𝗻𝘀𝗶𝘁𝗶𝗼𝗻 𝗠𝗮𝗸𝗲𝘀 𝗔𝘀𝘆𝗻𝗰 𝗢𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀 𝗦𝗺𝗼𝗼𝘁𝗵𝗲𝗿!
haitham medhat
haitham medhat

Posted on

𝗚𝗼𝗼𝗱𝗯𝘆𝗲 𝘂𝘀𝗲𝗦𝘁𝗮𝘁𝗲 𝗳𝗼𝗿 𝗟𝗼𝗮𝗱𝗶𝗻𝗴 𝗦𝗽𝗶𝗻𝗻𝗲𝗿𝘀: 𝗛𝗼𝘄 𝘂𝘀𝗲𝗧𝗿𝗮𝗻𝘀𝗶𝘁𝗶𝗼𝗻 𝗠𝗮𝗸𝗲𝘀 𝗔𝘀𝘆𝗻𝗰 𝗢𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀 𝗦𝗺𝗼𝗼𝘁𝗵𝗲𝗿!

Handling loading spinners during async operations is common, but the traditional approach using useState can lead to redundant re-renders and less organized code.


 const [loading, setLoading] = useState(false);

useEffect(() => {
 const fetchData = async () => {
 setLoading(true);
 try {
 const response = await fetch('/api/data');
 setLoading(false);
 return response;
 } catch (error) {
 setLoading(false);
 }
 }; 
 fetchData();
}, []);
Enter fullscreen mode Exit fullscreen mode

While effective, this method requires manually toggling the state, increasing boilerplate and risking errors.

𝗪𝗵𝘆 𝗨𝘀𝗲 𝘂𝘀𝗲𝗧𝗿𝗮𝗻𝘀𝗶𝘁𝗶𝗼𝗻 𝗜𝗻𝘀𝘁𝗲𝗮𝗱?

With useTransition, you can prioritize updates and streamline loading logic:


 const [isPending, startTransition] = useTransition();
 startTransition(async () => {
 try { 
const response = await axios.post('/api/endpoint', { title, content });
 if (response.data.responseCode === 201) { showSuccessToast(response.data.responseMessage); router.push('/dashboard');
 } 
} 
catch (error) { 
showErrorToast(error?.response|| "An error occurred"); }
 }
);  

Enter fullscreen mode Exit fullscreen mode

𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀:

  • No Manual State Management: React handles the isPending state for you.
  • Fewer Re-Renders: Updates are deferred, improving performance.
  • Cleaner Code: Focus on the logic, not the spinner.
  • React’s useTransition is a great tool for enhancing performance and reducing complexity. Have you used it yet? Share your experience!

Top comments (2)

Collapse
 
haitham_medhat_faff3c8959 profile image
haitham medhat

thanks for your advice, next time i will clearfiy the topic in more words and with clear example, for axios part the code is just to give an idea about use transition it's not about axios i just focus on the hook it's self