简体   繁体   中英

Why state is not getting updated here?

import { useEffect } from "react";
import { useRef } from "react";
import { useState } from "react";

const Button = () => {

    const [counter, setCounter] = useState(0)
    const btnRef = useRef();


    useEffect(() => {
        btnRef.current.addEventListener('click', function () {
            setCounter(counter => 1);
            console.log('counter ', counter);
        })
    },[])

    return (
        <button ref={btnRef}>Click Me</button>
    )
}

export default Button;

On each click of button, console shows only '0', why setCounter is not updating the state here ?

import { useEffect } from "react";
import { useRef } from "react";
import { useState } from "react";

const Button = () => {
  const [counter, setCounter] = useState(0);
  const btnRef = useRef();

  console.log(counter)

  useEffect(() => {
    btnRef.current.addEventListener("click", function () {
      setCounter((counter) => 1);
    });
  }, []);

  return <button ref={btnRef}>Click Me</button>;
};

Thanks to @Yousaf for explaining the closure issue in comments:

You also have a problem because of closure of the event listener function over the initial value of the counter state

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM