Last Updated : 23 Jul, 2025
In ReactJS we have a useState Hook this hook is used to declare a state variable inside a function. It should be noted that one use of useState() can only be used to declare one state variable.
Prerequisites:Syntax:
const [ element , setElement ] = useState(initial_state);Approach:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Project structure: It will look like the following.
Project structureThe 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",
}
Example: Change the state of the element using the setElement function.
JavaScript
import React, { useState } from 'react'
import './App.css'
function App() {
const [element, setElement] = useState(0);
function onClickButtonHandler() {
setElement(element + 1);
}
return (
<div className='App'>
<h1>GeeksforGeeks</h1>
<p>Add = {element}</p>
<button onClick={onClickButtonHandler}>
ADD
</button>
</div>
)
}
export default App;
CSS
/* Write CSS Here */
.App {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
body {
background-color: antiquewhite;
}
p {
font-size: 25px;
color: rgb(0, 167, 228);
font-weight: bold;
}
button {
width: 10em;
height: 2em;
background-color: rgb(27, 24, 24);
font-weight: 600;
font-family: 'Lucida Sans', 'Lucida Sans Regular',
'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
color: white;
border-radius: 6px;
border: none;
}
button:hover {
background-color: rgb(96, 145, 125);
}
Step to run the application: Open the terminal and type the following command.
npm start
Output:
OutputRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4