Side-effects
For side-effects other than simply changing the application state we'll be using the useEffect
hook. There's three parts to each useEffect
hook: setup
, cleanup
, and dependencies
where cleanup
and dependencies
are optional.
Setup
The setup is where all the hook's logic is placed.
Hook written like that will run on each render, and create a myriad of event listeners.
In fact this code will break your browser.
Cleanup
The setup can return a function that will be called when its time to "undo" the changes the hook has made.
Dependencies
We really only want the hook to run once:
Second argument to the useEffect
function is the array of dependencies. Hook behavior changes depending what's in it:
null
orundefined
: the hook will run for every render[]
(empty array): the hook will run once, after the first render[value1, value2]
: the hook will only run when one of the values changes
Resources
Last updated