Sponsor Me On GitHub!

UseEffect In Next.JS - React Hooks


Benjamin Carlson / March 14, 2021

1 min read––– views


React hooks allow you to perform side effects in function components. In this post, we will take a look at useEffect and give examples of how to use in in next.js.

Using useEffect In Next.JS

Let's take a look at an example. We will use useEffect to add an event listener to handle when a user scrolls. We will then log to the console the scrollY value. This is how this website dynamically adds the css to the nav bar on scroll!

First, we will import useEffect from react.

import React, { useState, useEffect } from 'react'

Next, call the method:

useEffect(() => {

We can add anything we want in here. Let's add our event listeners:

useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll)

Finally, create the handle scroll method and log the scrollY value to the console:

const handleScroll = () => {

And that's it! Check out my YouTube channel for more coding tutorials!

Share on TwitterEdit on GitHub

Sponsor Benjamin Carlson on GitHub Sponsors

Hi 👋 I'm Benjamin Carlson, a senior college student studying computer science. I post weekly tutorial videos on my YouTube channel and build cool open source projects!