React batch rendering doesn’t seem to work properly leading to flickering

I just started learning React and I am creating a shortening URL application to play around with the tools. Below is the overall architecture of my program that would be helpful for the question that I would like to ask.

Both the Home and UrlForm components have access to the UrlContext dispatcher to modify the state of the urls. I am trying to implement pagination to my application, the endpoint to retrieve all the urls associated to this user is /api/urls?size=5&page=0 (I’ve hardcoded the pagination for now to tackle the issue.

Just to summarise:

UrlForm button -> handleSubmit -> useCreateShortUrl -> creates URL in the backend -> dispatch to update the URL -> call getURL endpoint to retrieve the latest paginated URLs -> dispatch to update the URL state in React

export default function UrlForm() {
    const [longUrl, setLongUrl] = useState(""); 
    const { createShortUrl, shortUrl, error, isLoading }= useCreateShortUrl(); 

    async function handleSubmit(e) { // event handler that will allow batch rendering
        e.preventDefault(); 

        await createShortUrl(longUrl); 
    }
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useUrl } from "../contexts/UrlContext";
import { useAuth } from "../contexts/AuthContext";


export function useCreateShortUrl() {
    const { token } = useAuth(); 
    const { dispatch } = useUrl(); 

    const [error, setError] = useState(null); 
    const [isLoading, setIsLoading] = useState(false); 
    const [shortUrl, setShortUrl] = useState(""); 


    async function createShortUrl(longUrl) {
        const customHeaders = new Headers(); 
        customHeaders.append("Content-Type", "application/json"); 
        customHeaders.append("Authorization", `Bearer ${localStorage.getItem("token")}`); 

        const requestOptions = {
            method: "POST",
            headers: customHeaders, 
            body: JSON.stringify({longUrl}) 
        }
        try {
            const response = await fetch("api/urls", requestOptions); 

            const body = await response.json(); 
            if (!response.ok) {
                setIsLoading(false); 
                setError(body.message); 
                return;
            } 
            setError(null); 
            setIsLoading(false); 
            buildShortUrl(body.shortUrlId);  
            dispatch({ type: "CREATE_URL", payload: body }); 
            
            // updates the URL state to the correct pagination
            const secondRequestOptions = {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            };
            const secondResponse = await fetch("/api/urls?size=5&page=0", secondRequestOptions)
            const secondBody = await secondResponse.json(); 
            
            if (!secondResponse.ok) {
                setError(secondBody.message);
                setIsLoading(false); 
                return; 
            }
            setError(null); 
            setIsLoading(false); 
            let urls = []
            if (secondBody._embedded) {
                urls = secondBody._embedded.urls;
            }
            dispatch({ type: 'FETCH_URLS', payload: urls }); 
        } catch(e) {
            // server is probably down at this point
            // response body can't pe parsed into JSON
            setIsLoading(false); 
            setError("Server is down. Please try again later."); 
        }
    }

    function buildShortUrl(shortUrlId) {
        // todo: replace with domain name, make it more flexible by retrieving from .env 
        const urlFormatter = `http://localhost:3000/urls/${shortUrlId}`
        setShortUrl(urlFormatter); 
    }

    return { createShortUrl, shortUrl, error, isLoading }; 
}

I know I can fix this issue just by removing the dispatch({ type: "CREATE_URL", payload: body }); which wouldn’t send a render into the queue. But just for understanding, I’m not sure why having that would still cause the issue since React would do batch rendering after the event handler UrlForm::handleSubmit completes.

Image with debugger just before the issue

Image with debugger just after the issue (notice how there’s 6 images, that means the dispatcher caused React to render and hence now urls have 6 items)

Image at the end(notice now there’s only 5 times because after calling the fetch endpoint to retrieve the paginated urls, there should only be 5 URLs)

Side-question: How should I actually handle pagination when I create a new URL? Ideally I should only store the paginated number of URLs that’s requested by the user on the current page in the state (so I don’t have to store all the URLs from the database which could slow down the app) so that means I need a way to update the URL state everytime I create a URL just to maintain the correct number of URLs in the state to obey the paginated size.

New contributor

Rust57 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật