Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What is the use of setElement function in ReactJS ?

  • Last Updated : 01 Oct, 2021

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.


  • Create a React app to set up the development environment.
  • Declare a useState Hook.
  • Set the value of the element using the setElement function.

Note: Please refer to the ReactJS Setting up article to set up the development environment.

Setting development environment:

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

Note: In that created folder go to the src folder and delete App.test.js, logo.svg and setupTests.js because these files are not required in this project and our folder name is state

Project structure: It will look like the following.

Project structure


This useState Hook is declared as follows:

const [ element , setElement ] = useState(initial_state);

The value returned by useState() consists of an array with two values. The first value is known as the state variable and the second is referred to as a function to change the state of the state variable, this function is named as setElement.

This setElement function is used to change the state or value of the first variable.

Example: Change the state of the element using the setElement function.

In App.js write the code given below.


import React, { useState } from 'react'
function App() {
  const [element, setElement] = useState(0);
  function onClickButtonHandler() {
  return (
    <div style={{textAlign:"center"}}>
<p>Add = {element}</p>
      <button onClick={onClickButtonHandler}>
export default App;

Step to run the application: Open the terminal and type the following command.

npm start


Note: Please refer to the React Hook articles for a better understanding.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!