Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: React const function getting previous version of state value when calling the function. #28741

Closed
Waqas-Jani opened this issue Apr 4, 2024 · 1 comment

Comments

@Waqas-Jani
Copy link

React version:
React: 18.2.0
React Dom: 18.2.0

Link to code example:

const [popup, setPopup] = useState(false);

  useEffect(() => {
    if (popup) {
      document.getElementById("email-popup").style.visibility = "visible";
      document.getElementById("email-popup").style.opacity = "1";
    } else {
      document.getElementById("email-popup").style.opacity = "0";
      document.getElementById("email-popup").style.visibility = "hidden";
    }
  }, [popup]);
  
  const onClose = () => {
    console.log("=====Clicked Before Update====", popup);
    setPopup(false);
    console.log("=====Clicked After Update====", popup);
  };
  
  return (
   <span onClick={() => onClose()}>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="18"
                height="18"
                fill="#777"
                viewBox="0 0 16 16"
              >
                <path d="M2.146 2.854a.5.5 0 1 1 .708-.708L8 7.293l5.146-5.147a.5.5 0 0 1 .708.708L8.707 8l5.147 5.146a.5.5 0 0 1-.708.708L8 8.707l-5.146 5.147a.5.5 0 0 1-.708-.708L7.293 8 2.146 2.854Z" />
              </svg>
            </span>
);

The current behavior

Getting the old value for example. when try to call onClose function, in that function getting false value

The expected behavior

Should be true value when call onClose function on button click.

@Waqas-Jani Waqas-Jani added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Apr 4, 2024
@Waqas-Jani Waqas-Jani changed the title React const function getting previous version of state value when calling the function. Bug: React const function getting previous version of state value when calling the function. Apr 4, 2024
@eps1lon
Copy link
Collaborator

eps1lon commented Apr 4, 2024

This is a common pitfall. State values are more of a snapshot. The learning section "State as a snapshot" describes this in more detail. I hope that helps understand the issue better.

@eps1lon eps1lon closed this as not planned Won't fix, can't repro, duplicate, stale Apr 4, 2024
@eps1lon eps1lon added Resolution: Support Redirect and removed Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug labels Apr 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants