How to not trigger useEffect on router.push
Unanswered
Beveren posted this in #help-forum
BeverenOP
how to prevent useEffect fetching my data when i router.push into new session
const loadSession = useCallback((sessionId: string) => {
router.push(/session/${sessionId});
}, [router]);
This triggers my useEffect somehow. I have useEffect in my context and it looks like this:
const fetchSessions = useCallback(async (forceRefresh = false) => {
try {
let fetchedSessions: ISession[];
if (forceRefresh) {
fetchedSessions = await SessionService.fetchSessions();
} else {
const storedSessions = await getStoredSessions();
if (storedSessions.length > 0) {
return setSessions(storedSessions);
}
fetchedSessions = await SessionService.fetchSessions();
}
setSessions(fetchedSessions);
await saveSessionsToStorage(fetchedSessions);
} catch (error) {
console.error('Error fetching sessions:', error);
setSessions([]);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
fetchSessions();
}, [fetchSessions]);
const loadSession = useCallback((sessionId: string) => {
router.push(/session/${sessionId});
}, [router]);
This triggers my useEffect somehow. I have useEffect in my context and it looks like this:
const fetchSessions = useCallback(async (forceRefresh = false) => {
try {
let fetchedSessions: ISession[];
if (forceRefresh) {
fetchedSessions = await SessionService.fetchSessions();
} else {
const storedSessions = await getStoredSessions();
if (storedSessions.length > 0) {
return setSessions(storedSessions);
}
fetchedSessions = await SessionService.fetchSessions();
}
setSessions(fetchedSessions);
await saveSessionsToStorage(fetchedSessions);
} catch (error) {
console.error('Error fetching sessions:', error);
setSessions([]);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
fetchSessions();
}, [fetchSessions]);
3 Replies
BeverenOP
Should I move useEffect out of my context?
I think you should consider refactoring your whole code to not depend on an Effect.
Also useCallback isn’t supposed to be used to avoid your functions to trigger effects by keeping the same function reference, should be used as a performance improvement and removing it from your code should not break the functionality. Seems like here it’ll all brake if you remove the useCallback hooks
Also useCallback isn’t supposed to be used to avoid your functions to trigger effects by keeping the same function reference, should be used as a performance improvement and removing it from your code should not break the functionality. Seems like here it’ll all brake if you remove the useCallback hooks
See if you can fetch the session server side and pass the data down to your client components instead of making your components fetching it in Effects. If you need it to be on the client maybe consider a library like React Query to make that logic way easier and avoid issues