Preventing flash when using setQueryData before navigation
#10970
-
Preventing flash when using
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Yes — this is exactly what The flash happens because The clean way is to suppress notifications only during the save → navigate window, using the function form so normal rendering (including the initial const isNavigatingAway = useRef(false);
const { isPending, isError, data } = useQuery({
queryKey: ['article', id],
queryFn: fetchArticle,
// function form: return [] to notify on nothing, undefined for default tracking
notifyOnChangeProps: () => (isNavigatingAway.current ? [] : undefined),
});
const mutation = useMutation({
mutationFn: saveArticle,
onSuccess: (saved) => {
isNavigatingAway.current = true; // stop this observer re-rendering
queryClient.setQueryData(['article', saved.id], saved); // cache updated, no flash here
navigate(`/articles/${saved.id}`); // destination reads the fresh cache → no fetch, no flash
},
});Why this beats the Two notes:
|
Beta Was this translation helpful? Give feedback.
Yes — this is exactly what
notifyOnChangePropsis for.The flash happens because
setQueryDatanotifies every active observer of that query key — including theuseQueryon the edit page you're about to leave.notifyOnChangePropsis set per-observer, so you can silence the edit page's observer without affecting the destination page's observer at all. The cache still updates (so the destination renders instantly); the edit page just doesn't re-render.The clean way is to suppress notifications only during the save → navigate window, using the function form so normal rendering (including the initial
pending → success) still works: