I am building a project using next.js but I have an issue that getServerSideProps is called 6 times when the page is rendered.
Here is the code at the top in pages.
const NewFindstay: React.FC<INewFindstayProps> = ({ findstayList }) => {
const [isMap, setIsMap] = useState(false);
return (
<div id="contents">
<FindstayFilter setIsMap={setIsMap} isMap={isMap} />
<FindstayList findstayList={findstayList} isMap={isMap} />
</div>
);
};
export async function getServerSideProps({ query, req }) {
let findstayList = null;
try {
findstayList = await getPlaceListAsync(
{ ...query },
req.headers.cookie ? req.headers.cookie : null
);
} catch (e) {
findstayList = null;
}
return {
props: {
findstayList,
query,
},
};
}
export default NewFindstay;
Seems this is caused by components that imported inside of FindstayFilter. (let's say components A, B, C, D, E, F)
Each components of A, B, C, D, E, F has useEffect hook for setState.
// A
useEffect(() => {
if (router.query.city) {
setSelectedCity(router.query.city);
};
}, [router.query.city]);
// B
useEffect(() => {
setDateRange({
startDate: check_in ? moment(check_in) : null,
endDate: check_out ? moment(check_out) : null
})
}, [router.query.check_in, router.query.check_out]);
// C
useEffect(() => {
const queryPrice = {
min: price_min ? (parseInt(price_min as string, 10) / 10000) : 0,
max: price_max ? (parseInt(price_max as string, 10) / 10000) : 100
}
setRangePrice(queryPrice);
}, [router.query.price_min, router.query.price_max]);
// D, E, F use same pattern as well.
In order words, when FindstayFilter component renders, useEffect hook inside A, B, C, D, E, F rerender the component total 6 times which triggers calling getServerSideProps 6 times as well.
How can I minimize calling getServerSideProps? should I use useEffect hook only inside of FindstayFilter component and crammed many setstate code into the hook?