I have a parent component which has a isLoading
useState
and read params from the URL and pass them to child component:
export function MainUserDetails() {
const [isLoading, setIsLoading] = React.useState<boolean>(false);
const { t } = useTranslation();
const params = useParams();
const userId = params.userId as string;
const handleLoadingStateChanged = React.useCallback((loading: boolean) => {
setIsLoading(loading);
}, []);
const MemoizedUserDetailsForm = React.useMemo(
() => <UserDetailsForm userId={userId} onLoadingStateChanged={handleLoadingStateChanged} />,
[userId, handleLoadingStateChanged]
);
return (
<Stack spacing={4}>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={3} sx={{ alignItems: 'flex-start' }}>
<Box sx={{ flex: '1 1 auto' }}>
<Typography variant="h4">User Details</Typography>
</Box>
<Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>{isLoading && <CircularProgress />}</Box>
</Stack>
{isLoading ? <Skeleton variant="rounded" height={500} /> : <>{MemoizedUserDetailsForm}</>}
</Stack>
);
}
In my child component inside useEffect
I am fetching the component’s data and the useEffect
has a dependencies of the userId
(which is being send from the parent component):
React.useEffect(() => {
const fetchBusinesses = async () => {
try {
const businesses = await getBusinesses(businessFilters);
if (businesses.status === 'success') {
setBusinesses(businesses.data);
}
} catch (error) {
logger.error(`[UserDetailsForm/#fetchBusinesses]: Failed to fetch businesses:`, error);
}
}
const fetchData = async () => {
if (userId) {
onLoadingStateChanged?.(true);
await fetchBusinesses();
onLoadingStateChanged?.(false);
}
};
fetchData();
}, [userId]);
My problem is that in this way, one of the components (I guess it’s the parent one) is re-renders endlessly, when commenting out the onLoadingStateChanged
from the fetchData
function, it downloads the data once and everything is working fine.
I already changed the onLoadingStateChanged
to use memoize function and also now the whole UserDetailsForm
is memoize, but still the problem persists.
How can I overcome this problem?