re: Hide menu when scrolling in React.js VIEW POST


Perfect! As a final step, you could also change a bit the setState. Instead of having to write 3 times setState, you could do:

handleScroll = () => {
  const { prevScrollpos } = this.state;

  const currentScrollPos = window.pageYOffset;
  const visible = prevScrollpos > currentScrollPos;

    prevScrollpos: currentScrollPos,

It would be better to check if scroll direction (-Y or Y+) is the same with previous scroll direction. If it is the same, you don't have to update the state, because the component has the same position. By this I mean, if you already have the component hidden, and you keep scrolling down, you don't need to update its state.

And to be fair, I would add a debounce function wrapper to avoid calling this handler too many times (for performance reasons). Look into debounce method of "underscore" node modules. It's pretty easy to implement, and saves a lot of memory.

As always, simple problems have complex solutions. :)

Done! Thanks for your good advice 🌟

code of conduct - report abuse