The Many Effects of useEffect

Aimee
Nerd For Tech
Published in
3 min readApr 16, 2021
Image credits to Aditya Loshali and freeCodeCamp

Another React Hook I’ve enjoyed learning and working with, aside from useContext, is useEffect.

useEffect is a React Hook that mimics component lifecycles and provides this to functional components. In class components, you have life cycles such as componentDidMount() or componentDidUpdate(). Life cycles are used for the purpose of rendering and re-rendering the DOM based on component updates.

Similar to useContext, as the industry standard moves from class components to functional components, we still need a Hook to address this issue. useEffect is built for that purpose. In fact, the official React documentation says that the useEffect Hooks is like “componentDidMount, componentDidUpdate, componentWillUnmount combined”.

Image credits to LogRocket

How do you use it?

The useEffect, like useContext, has to be imported into your component from React. In this case, a useEffect should be invoked after you declare your functional component, and before your return statement.

The Hook itself “can accept 2 parameters, [which are] a callback function…and dependencies array” (Olena Drygalya).

import {useEffect} from 'react'export default function TestCase(){
useEffect(() => {
/* your callback function goes here()*/
}, [/* your dependency array goes here */])
}

The first parameter, the callback function, is also known as a side effect. That’s because “we usually want to execute side effects after specific conditions, e.g., data has changed, a prop has changed, or the user first sees our component” (Sebastian Weber).

The second parameter of a dependency array assures that the useEffect is only run or re-render if there are changes or mutations to the dependency array. More likely than not, you might’ve seen the dependency array assigned to the value of an empty array. This assures that the useEffect is invoked once.

React Hooks and functional components aren’t going anywhere — if anything, it seems like developers are pretty enthusiastic about using Hooks since their introduction. React Hooks does an equally, if not better, job than class components in terms of efficiency and readability as well, with less code doing the same work and logic.

If you haven’t used React Hooks or useEffect previously, are new to React, or want to learn more about Frontend development, I encourage you to give the below resources a read.

--

--