useEffect() Hook in Next.JS - React Hooks

Learn what useEffect is learn how to use useEffect in Next.JS.

What Are React Hooks?

Released in React 16.8, React Hooks allow you to you use state and other React features without writing a class.

Here is a simple example from the website:

import React, { useState } from 'react'; // <--- import the hook

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0); // <--- useState is the hook

  return (
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me

As you can see, we can create a state variable named count in only one line using the useState hook.

Using useEffect In Next.JS

Adding the useEffect() (or Effect Hook) hook in Next.js is not at bad as one would think. 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!


Import useEffect from react

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

Call the method and add code

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!

Published on August 09, 2021 (3 months ago) in

View Related Posts

6 months ago


Add Comments To React/Next.js Website

2 months ago


Advanced Chakra UI

3 months ago


useEffect() Hook in Next.JS - React Hooks

6 months ago


Add Google Analytics To Next.js Website

4 months ago


Add Splitbee Analytics To Next.js

1 month ago


Generate A Dynamic Sitemap In Next.js Website

3 days ago


Next/Image Doesn't Fill Parent Div!

6 months ago


Next.js + MDX Pages Quickstart

Was this snippet helpful?

Written By Benjamin Carlson


More Articles By Benjamin Carlson




Privacy Policy

Carlson Technologies Logo© Copyright 2021, Carlson Technologies LLC. All Rights Reserved.

Powered by

Vercel Logo