React useEffect Hook
An introduction on how to use useEffect Hook in your React application
Wednesday, November 10, 2021
What is a useEffect Hook?
TL;DR
React
useEffectis an alternative to the "old"classlifecycle 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.
Longer version
Before
React v16.8, we can only enable a component to react to state changes using lifecycle methods.
How to define a useEffect
.jsx123456Here's a quick explanation of the above code:
- We can declare an effect by calling either React.useEffectoruseEffect.
- effectis the function that will be called when the component is mounted. OR when the dependency array changes.
- cleanupis the function called when the effect is "unmounted".
- dependency arrayis the array of values passed as a second argument to the- effectfunction.- If there is no dependency array, the effect will be called every time the component is mounted.
- If the array is empty, the effect will be called only once when the component is mounted.
- If the array is not empty, the effect will be called every time the component is mounted and the dependency array changes.
 
Examples
Increment a counter every second until it reaches 10
.jsx12345678910111213141516Basic fetch from an API
.jsx1234567891011Fetching with loading indicator + error handling - then/catch/finally
.jsx1234567891011121314151617181920212223Fetching with loading indicator + error handling - async/await
.jsx123456789101112131415161718192021222324Store a value in localStorage everytime the key or value changes
.jsx12345678910OR mimic a class lifecycle method
Check this blog on how to convert a class lifecycle methods to
useEffecthooks
Additional Note
- useEffectcan only be used in functional components
- The order of useEffectdeclarations is important.
- useEffectin a custom hook is a great way to promote side effect reusability. I will discuss this in another blog.
Conclusion
Compared to the old lifecycle methods, useEffect is much more powerful and flexible, making it an ideal choice when managing a side-effect.