React useEffect Hook
An introduction on how to use useEffect Hook in your React application
November 10th, 2021
November 10th, 2021
useEffect
Hook?TL;DR
React
useEffect
is an alternative to the "old"class
lifecycle methods/hooks. It is used to manage side effects, such as network requests or run a piece of code when the component is mounted, updated, or unmounted.
Before
React v16.8
, we can only enable a component to react to state changes using lifecycle methods.
useEffect
React.useEffect
or useEffect
.effect
is the function that will be called when the component is mounted.
OR when the dependency array changes.cleanup
is the function called when the effect is "unmounted".dependency array
is the array of values passed as a second argument to the effect
function.then/catch/finally
async/await
Check this blog on how to convert a class lifecycle methods to
useEffect
hooks
useEffect
can only be used in functional componentsuseEffect
declarations is important.useEffect
in a custom hook is a great way to promote side effect reusability. I will discuss this in another blog.Compared to the old lifecycle methods, useEffect
is much more powerful and flexible, making it an ideal choice when managing a side-effect.