DEV Community

Sebin CM
Sebin CM

Posted on

4 3

Closures and useEffects

import { useState, useEffect} from "react";

export default function App() {
  const [count, setCount] = useState(0);

   useEffect(() => {
     setTimeout(() => {
       console.log(" ", count);
    }, 3000);
   }, []);

  return (
    <div className="App">
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>Click Me </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The above code will display the value of count when the component renders. In the meantime if we click the button and try to change the value of count. The value of count changes but the log will contain the value zero. This also happens when you are working with async function.

We can get around this problem by using useRef hook. The code is as follows.

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

export default function App() {
  const [count, setCount] = useState(0);
  const countRef = useRef(0);

  countRef.current = count;

  useEffect(() => {
    setTimeout(() => {
      console.log("useRef", countRef.current);
    }, 3000);
  }, []);

  return (
    <div className="App">
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>Click Me </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

using the above block of code we can get the current value of the variable while logging it to the console

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series