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();
}, []);
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"); }
}
);
๐๐ฒ๐ป๐ฒ๐ณ๐ถ๐๐:
- 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)
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