Home > Blockchain >  state inside function not updating
state inside function not updating

Time:02-07

Does anyone know why the state inside a function isn't updating and sometimes the btnRef in Ss file always null so the addEventListener not working

//App.tsx

import { useRef } from "react";
import "./styles.css";
import Ss from "./Ss";

export default function App() {
  const btnRef = useRef<any>(null);
  return (
    <div className="App">
      <Ss btnRef={btnRef.current} />
      <div ref={btnRef}>click</div>
    </div>
  );
}
//Ss.tsx
import { useEffect, useState } from "react";

export default function Ss({ btnRef }: { btnRef?: Element }) {
  const [current, setCurrent] = useState(0);
  function asd() {
    console.log("current:", current);
    setCurrent((prev) => prev   1);
  }
  useEffect(() => {
    btnRef?.addEventListener("click", asd);
  }, [btnRef]);

  return <></>;
}

CodePudding user response:

btnRef.current in <Ss btnRef={btnRef.current} /> will be null because you are passing it to Ss before the div is even mounted on the DOM.

<Ss btnRef={btnRef.current} />
<div ref={btnRef}>click</div>

Since the App is not re-rendered after that , btnRef prop in Ss is still null.

CodePudding user response:

import { useEffect, useState } from "react";

export default function Ss({ btnRef }: { btnRef?: Element }) {
  const [current, setCurrent] = useState(0);
  function asd() {
    let tempCurrent = current   1               // 
    console.log("current:", current);
    setCurrent(tempCurrent);              //
  }
  useEffect(() => {
    btnRef?.addEventListener("click", asd);
  }, [btnRef]);

  return <></>;
}

  •  Tags:  
  • Related