-
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
titleandreleaseYearof 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
getMoviesfunction as dependency inuseEffectto discuss dependency array. -
Use result from last exercise (i.e. CodeSandBox: fetch movies)
-
Fix issues with help of
react-hooks/exhaustive-depsrule. -
- Move into
useEffecthook
- Move into
-
- Wrap in
useCallbackhook
- 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
activevalue and thefetchDatacallback function. - The cleanup function of the effect belongs to the closure and so settings
active = falsechanges the value of theactivevariable in the closure. - The cleanup function is run for every effect but the last one. Hence, the
activevalue is onlytruefor 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
useDatahook (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.