-
Run side-effects after mount/update of a component (runs asynchronously).
-
Data fetching
-
Task: Start CodeSandBox: fetch movies (starter code) to fetch movies from https://reactnative.dev/movies.json on mount and display
title
andreleaseYear
of the first movie in the list. -
Result: CodeSandBox: fetch movies
Dependency array (and react-hooks/exhaustive-deps
rule and useCallback
hook)
-
Mental model: Don't think of dependencies as values which trigger lifecycle events (i.e. when the effect should re-run). An effect bundles functionality given dependencies.
-
empty dependency array (
[]
) might be an exception. -
Add
getMovies
function as dependency inuseEffect
to discuss dependency array. -
Use result from last exercise (i.e. CodeSandBox: fetch movies)
-
Fix issues with help of
react-hooks/exhaustive-deps
rule. -
- Move into
useEffect
hook
- Move into
-
- Wrap in
useCallback
hook
- Wrap in
When implementing data fetching with a useEffect hook, you have to precent race conditions
-
Problem: CodeSandBox (JS) with race condition
-
Solution: CodeSandBox (JS) solution code
Explanation:
- Every new effect opens up a new closure which closes over the
active
value and thefetchData
callback function. - The cleanup function of the effect belongs to the closure and so settings
active = false
changes the value of theactive
variable in the closure. - The cleanup function is run for every effect but the last one. Hence, the
active
value is onlytrue
for fetch which was initiated last.
- Every new effect opens up a new closure which closes over the
-
Recommendation: Use an external fetching library or create a
useData
hook (as illustrated here)
React 18 StrictMode
helps you spot bugs related with a forgotten useEffect
cleanup function (if needed) by remounting every component once immediately after its initial mount in development.
Step 3 in this article of the new React docs explains it nicely.
- See also the discussion in the new React docs section "You Might Not Need an Effect"
- Example copied and adapted from this blog post of Max Rosen.