I'm building a page similar to TMDB Popular Movies section: https://www.themoviedb.org/movie
with a button that fetches more data to be displayed. The first page of results is delivered by getStaticProps(), after that I only want to fetch data client side. I've noticed that every time I click on something (either to display sorting tab/options or to load more content), it not only triggers multiple re-renders but it is not until the second re-render that the data gets set. To be exact, the Load More button triggers four re-renders, and clicking on the sorting tab triggers two. Is there a way I could make this more efficient?
const PopularMediaPage = ({json, title, url}) => {
const [isShowed, setIsShowed] = useState(true); // This serves to display the "Sort Results By" tab
const [showSort, setShowSort] = useState(false); // This displays the actual list of sorting options
const [typeOfSort, setTypeOfSort] = useState("Popularity Descending");
const [media, setMedia] = useState(json.results);
const [shouldFetch, setShouldFetch] = useState(false);
const count = useRef(1);
const isMovie = json.results.every(e => e.hasOwnProperty("release_date"));
const sortMap = [
{name: "Popularity Descending", query:"&sort_by=popularity.desc"},
{name: "Popularity Ascending", query:"&sort_by=popularity.asc"},
{name: "Rating Descending", query:"&sort_by=vote_average.desc"},
{name: "Rating Ascending", query:"&sort_by=vote_average.asc"},
{name: "Release Date Descending", query: isMovie ? "&sort_by=release_date.desc" : "&sort_by=first_air_date.desc" },
{name: "Release Date Ascending", query: isMovie ? "&sort_by=release_date.asc" : "&sort_by=first_air_date.asc" },
];
const sortQuery = sortMap.filter(e => e.name === typeOfSort ? e.query : null)[0]
const {data, error} = useSWR(shouldFetch && `${url}&page=${count.current}${sortQuery.query}`, fetcher)
useEffect(() => {
data && setMedia([...media, ...data]);
return setShouldFetch(false);
}, [media, data])
const handleLoadMore = () => {
setShouldFetch(true);
count.current += 1;
};
return (
//...layout and html elements
<SortingTab /> // with list of sorting options inside
<PopularMediaResults /> // actual results to be displayed
<button type="button"
onClick={handleLoadMore}>Load More</button>
)