We use the
useEffect hook for calling functions with side effects within our components.
useEffect hook takes 2 arguments:
callback- a function with side effects
dependencies- an optional array containing dependency values
When our component function runs, the
callback will be called if any
dependencies have changed since the last time the component function ran.
Here, we use
useEffect to change the background color to blue when
count is a multiple of 5. The
callback is called every time the
color changes, since
color is listed as a dependency.
Undefined or empty dependency array
If the dependency array is empty or
useEffect will have a different behavior.
callbackis called only once, right after the component renders for the first time
callbackis called on every component render (every time the component function runs)
Here the dependency array is
undefined, so our
callback will run every time our component function runs, e.g. any time we click the button and
useState tells our component to re-run.
Here the dependency array is empty, so our
callback will only run once (and permanently set a page background color).