reactjssetinterval

React Hooks and Events


  var [testVar,setTestVar]=useState(0)

  var showTestVar=()=>{
    console.log(testVar)
  }

  var effectTest=()=>{
    setTestVar(1)
    setInterval(showTestVar,1000)
  }

I want to have a function called showTestVar that is called whenever an event occurs. Firing from setInterval in this case. I want it to be called whether or not testVar has changed, but on every event. How do I achieve this with Hooks?

As it is, the log shows 3 outputs every second, 1 zero and 2 ones.


Solution

  • You might want to check useRef so you can keep it in sync with the state.

    const { useState, useRef, useEffect}  = React;
    
    const App = () => {
      const [testVar, setTestVar] = useState(0);
      const testVarRef = useRef(testVar);
    
      useEffect(() => {
        testVarRef.current = testVar;
      }, [testVar]);
    
      const showTestVar = () => {
        console.log(testVarRef.current);
      };
    
      const effectTest = () => {
        setTestVar(1);
        setInterval(showTestVar, 1000);
      };
    
      return <button onClick={effectTest}>Start</button>;
    };
    
    ReactDOM.createRoot(
        document.getElementById("root")
    ).render(
        <App />
    );
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>