Blog

UseEffect In Next.JS - React Hooks

BC

Benjamin Carlson / March 14, 2021

1 min read––– views

Introduction#

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 = () => {
        console.log(scrollY)
    }

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

Share on TwitterEdit on GitHub
Image of coffee

Coffeeclass

Coffeeclass is a tutorial website I started to teach programming and computer science skills in a fun and easy to learn manner.

Sponsor Benjamin Carlson on GitHub Sponsors

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

/hello/videos