Tech Lead/Team Lead. Senior WebDev.
Intermediate Grade on Computer Systems-
High Grade on Web Application Development-
MBA (+Marketing+HHRR).
Studied a bit of law, economics and design
Location
Spain
Education
Higher Level Education Certificate on Web Application Development
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).
As a good practice, I would suggest to convert this into a customHook like that:
so you can use it in multiple places like:
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).
Even better