DEV Community

Discussion on: How to solve "window is not defined" errors in React and Next.js

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

As a good practice, I would suggest to convert this into a customHook like that:

import { useEffect } from 'react';

export default function useScroll(callback) {
  useEffect(function mount() {
    function onScroll() {
      const scrollPosition = window.scrollY;
      callback(scrollPosition);
    }

    window.addEventListener('scroll', onScroll);

    return function unMount() {
      window.removeEventListener('scroll', onScroll);
    };
  });

  return null;
}

so you can use it in multiple places like:

import useScroll from '../customHooks/useScroll';

export default function whatever() {

  useScroll( (val) => { 
     // add any logic with val
  });

  // component logic
  return (  {/*component structure*/} );

This is just an example, it can be extended adding an "element" parameter and some logic for it in the hook so you can get the scroll position of any element and get back the value to do something with it in the callback.

This avoid the need of creating different functions that performs almost the same actions and it's more in line with what hooks are (high order functions).

Collapse
 
acushlakoncept_31 profile image
Uduak Essien

Even better