Skip to content

Latest commit

 

History

History
50 lines (29 loc) · 2.88 KB

useEffect.md

File metadata and controls

50 lines (29 loc) · 2.88 KB

useEffect

Dependency array

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 in useEffect to discuss dependency array.

  • Use result from last exercise (i.e. CodeSandBox: fetch movies)

  • Fix issues with help of react-hooks/exhaustive-deps rule.

    1. Move into useEffect hook
    1. Wrap in useCallback hook

useEffect hook race conditions when fetching data

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:

    1. Every new effect opens up a new closure which closes over the active value and the fetchData callback function.
    2. The cleanup function of the effect belongs to the closure and so settings active = false changes the value of the active variable in the closure.
    3. The cleanup function is run for every effect but the last one. Hence, the active value is only true for fetch which was initiated last.
  • Recommendation: Use an external fetching library or create a useData hook (as illustrated here)

React 18: useEffect hooks and StrictMode

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.

Notes