Skip to content

State variable not updating in useEffect callback? #14066

Closed
@evolutionxbox

Description

@evolutionxbox

Do you want to request a feature or report a bug?
Bug, maybe? Although thinking about it more makes me think I've misunderstood something.

What is the current behavior?
scroll state variable updates in rendered output but not inside handleScroll event callback.

I reckon this might be due to the fact that when handleScroll is defined scroll is 0, but scroll is defined in the scope above and should be updated when the component is re-rendered.

import React, { useState, useEffect } from "react";

const Scroller = () => {
  const [scroll, setScroll] = useState(window.scrollY);

  const handleScroll = () => {
    console.log(scroll); // scroll is always 0
    setScroll(window.scrollY);
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []); // runs once

  return <div id="scroll">{scroll}</div>; // scroll is correct
};

export default Scroller;

Please have a play:
Edit yv8vwo44px

What is the expected behavior?
scroll to be updated inside handleScroll event callback and in render output.

Which versions of React, and which browser / OS are affected by this issue?

chrome        70.0.3538.77
react         16.7.0-alpha.0 - next
react-dom     16.7.0-alpha.0 - next

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions