Accessing state in setTimeout React.js
Last Updated :
25 Jul, 2024
We frequently deal with timeouts when developing different applications with React. A setTimeout method enables us to invoke a function after a particular interval. However, implementing the conventional setTimeout in React can be difficult.
Prerequisites:
Steps to Create the React Application:
Step 1: Make a project directory, head over to the terminal, and create a react app named counter using the following command:
npx create-react-app counter
Step 2: After the counter app is created, switch to the new folder counter by typing the command below:
cd counter
Project Structure:
Final Directory Structure Th updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Approach:
- The useState hook defines a state inside a functional component. The count variable serves as the state variable, and the setCount function allows us to modify the count.
- React will regenerate the setTimeout method each time the component is re-rendered, setting a new timeout. Therefore, we must use the useEffect hook with an empty dependency array to create a timeout after the component mounts.
- We will pass the logic and the delay argument inside the setTimeout method.
- After 3 seconds, the count will be console logged.
- We have a button to increment the count.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<meta name="theme-color"
content="#000000" />
<meta name="description"
content="Web site created using create-react-app" />
<title>Counter App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
CSS
/* App.css */
.counter {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border: 4px solid darkGreen;
margin: 2rem;
}
.btn {
font-size: 1rem;
margin: 1rem;
background-color: darkgreen;
color: white;
padding: 1rem;
cursor: pointer;
border-radius: 10px;
}
JavaScript
//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
JavaScript
//App.js
import { useEffect, useState } from "react";
import './App.css';
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
console.log(count);
}, 3000);
}, []);
return (
<div className="counter">
<h2>{count}</h2>
<button className="btn"
onClick={() => setCount(count + 1)}>
Press to increment the count
</button>
</div>
);
}
export default App;
Step to run the application: Run the application by using the following command:
npm start
Output: You can access it at localhost:3000 on your browser.
Example 2: The useState hook defines a state inside a functional component. The count variable serves as the state variable, and the setCount function allows us to modify the count.
JavaScript
import { useEffect, useState, useRef } from "react";
import './App.css';
function App() {
const [count, setCount] = useState(0);
//creating a reference object
const countRef = useRef(count);
countRef.current = count;
useEffect(() => {
setTimeout(() => {
//accessing the current state of the counter
console.log(countRef.current);
}, 3000);
}, []);
return (
<div className="counter">
<h2>{count}</h2>
<button className="btn"
onClick={() => setCount(count + 1)}>
Press to increment the count
</button>
</div>
);
}
export default App;
Step to Run the application: Run the application by using the following command:
npm start
Output: