tezvyn:

Refetching data when a screen gains focus

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

knowing focus differs from mount.

OUTLINE

use useFocusEffect with a useCallback callback; refetch on focus; clean up to abort stale requests.

RED FLAG

relying on useEffect with empty deps, which only fires once on mount.

WHAT THIS TESTS Understanding the React Navigation lifecycle. Screens in a stack stay mounted when you push another screen on top, so component mount and screen focus are different events. A naive useEffect with an empty dependency array runs only once and will not refetch when the user navigates back.

A GOOD ANSWER COVERS Use the useFocusEffect hook. It runs its callback every time the screen gains focus and runs the returned cleanup when it loses focus. Crucially, wrap the callback in useCallback with the right dependencies, otherwise it re-subscribes on every render. Inside, call your fetch function; in the cleanup, abort the request with an AbortController or set a cancelled flag so a slow response from a screen you already left does not set state on an unfocused screen. For purely conditional rendering you can instead read the boolean from useIsFocused.

COMMON WRONG ANSWERS Using useEffect with an empty array and expecting it to fire on every visit. Adding a navigation listener manually when the hook already exists. Forgetting useCallback, which makes useFocusEffect run on every render and can cause request storms. Ignoring cleanup, leading to set-state-after-unmount style bugs and stale data overwrites.

LIKELY FOLLOW-UPS How is useFocusEffect different from useIsFocused? How would you debounce or skip the refetch if data is still fresh? How does this interact with React Query, whose refetchOnMount and focus refetch can replace manual logic?

ONE CONCRETE EXAMPLE Inside ProfileScreen you write useFocusEffect with a useCallback that creates an AbortController, calls fetchProfile passing controller.signal, and on success calls setProfile. The callback returns a function that calls controller.abort. Each time the user taps back to this tab the data refreshes, and if they leave mid-request the pending fetch is cancelled so it never resolves onto a screen the user has left.

Read the original → reactnavigation.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.