Hooks useEffect
One very important feature of Hooks is allowing function components to have access to the lifecycle hooks.
Using class components you can register a function on the componentDidMount
, componentWillUnmount
and componentDidUpdate
events, and those will serve many use cases, from variables initialization to API calls to cleanup.
Hooks provide the useEffect()
API. The call accepts a function as argument.
The function runs when the component is first rendered, and on every subsequent re-render/update. React first updates the DOM, then calls any function passed to useEffect()
. All without blocking the UI rendering even on blocking code, unlike the old componentDidMount
and componentDidUpdate
, which makes our apps feel faster.
Example:
The same componentWillUnmount
job can be achieved by optionally returning a function from our useEffect()
parameter:
useEffect()
can be called multiple times, which is nice to separate unrelated logic (something that plagues the class component lifecycle events).
Since the useEffect()
functions are run on every subsequent re-render/update, we can tell React to skip a run, for performance purposes, by adding a second parameter which is an array that contains a list of state variables to watch for. React will only re-run the side effect if one of the items in this array changes.
Similarly you can tell React to only execute the side effect once (at mount time), by passing an empty array:
useEffect()
is great for adding logs, accessing 3rd party APIs and much more.
Example on Codepen:
Last updated