Geek Culture
Published in

Geek Culture

React Hook: useEffect

The useEffect hook is incredibly useful. It’s yet another handy feature released not too long ago as a React Hook, a way to manage component lifecycles and app state inside of functional components.

The useEffect hook essentially replaces the componentDidMount lifecycle function from a class component, but useEffect is used in a functional component.

UseEffect is most commonly used to set a piece of state to that component, fetch data, reading from or writing to local storage, or setting event listeners.

The main functionality is that the useEffect will happen upon the initial render of that component, and allows for changes to re-render that component (items to be watched for change must be included in the dependency array, which we will touch on later).

The syntax

First and foremost, we’ll need to import the hook:

import {useEffect} from "react"

Then, inside of your functional component, useEffect to fetch data or set event listeners.

useEffect(() => {
*fetch data, set event listeners, etc*
}, [optional dependency array])

The dependencies…

The dependency array is optional, but is usually set to a list of items, either functions, variables, or state, that will be watched for change. If one of those items changes, the component will be re-rendered. If the dependency array is empty, the useEffect will run only once, upon the initial render of that component.

I highly recommend getting VERY familiar with this hook, as it is an amazing way to control side effects with an extra level of abstraction from our old friend “componentDidMount” in a class.

This is an amazing resource to dive DEEP into the useEffect hook, as well as some of the other hooks that are typically used in conjunction with it: The Last Guide to the useEffect Hook you will EVER need!

Cheers, and have fun with some side effects!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store