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