1

I wanna make the header invisible when i scroll down and when i scroll up make it visible

const [showHeaderState, setShowHeaderState] = useState(true);
      const prevScrollpos = useRef(window.pageYOffset);
    
      const handleScroll = () => {
        const currentScrollPos = window.pageYOffset;
        prevScrollpos.current < currentScrollPos
          ? setShowHeaderState(false)
          : setShowHeaderState(true);
        prevScrollpos.current = currentScrollPos;
      };
    
      useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => window.removeEventListener('scroll', handleScroll);
      }, []);
    
      console.log(showHeaderState);

this code is working

but when i log rendering state is show that is the component rendered two times

on scroll up log true two times

on scroll down log false two times

any solution ??

1 Answers1

2

Just because the console.log is running does not mean your component is actually rendering twice, as React can run portions of a component's function without committing those changes in a complete render. If you want to check to see if additional complete renders are occurring, place a console.log inside of an effect hook with no dependencies (that will run every time a re-render occurs):

useEffect(() => { console.log("render") })

And see how many times it is logged. It should only be run once per state change.

This answer provides a more complete explanation of this phenomenon.

Chris B.
  • 5,477
  • 1
  • 12
  • 30
  • oh, that is warking , thanks for your answer and explanation, but is this code is the best for make this idea, or there is better than it ? – Mustafa Wael Aug 21 '20 at 23:29