React Hooks: useEffect

Photo by Dave Phillips on Unsplash

In a previous post, I spoke about how I used useEffect to keep track of changes, and update components with said change. Here, I’ll dive a little deeper into what is going on behind my code.

So what is useEffect? useEffect is similar to componentDidMount and componentDidUpdate in the sense that it runs after the first render and after each update. With each run, useEffect executes the function passed into it. Let’s take a look at this example:

const [logoColor, setLogoColor] = useState("#FEFEFE")const location = useLocation()useEffect(() => {    switch (location.pathname) {        case "/about":            setLogoColor("#636363")            return logoColor        default:            setLogoColor("#FEFEFE")            return logoColor    }}, [location])

useEffect takes in two arguments: the function to be executed upon change, and the variable to be observed for changes as an array. I use another Hook, useLocation to check for changes in my window location. Whenever that gets updated, the switch statement runs, changing my logo color according to the path.

The second argument, [location], tells React not to execute the function if the location variable has not changed, which helps to improve performance!

--

--

--

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

Love podcasts or audiobooks? Learn on the go with our new app.

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
Chindalath Traymany

Chindalath Traymany

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

More from Medium

React Intro

React Redux ♻️

How to style React

about React