How to add an element to a useState array in React

0 votes
With the help of code can you tell me How to add an element to a useState array in React?
Mar 12 in Node-js by Ashutosh
• 23,230 points
42 views

1 answer to this question.

0 votes

You can use the spread operator (...) or the functional setState update.

Example:

import { useState } from 'react';

function App() {

    const [items, setItems] = useState([1, 2, 3]);

    const addItem = () => {

        setItems(prevItems => [...prevItems, 4]); // Adding new element

    };

    return (

        <div>

            <button onClick={addItem}>Add Item</button>

            <ul>

                {items.map((item, index) => <li key={index}>{item}</li>)}

            </ul>

        </div>

    );

}

export default App;

answered Mar 12 by Tanvi

Related Questions In Node-js

0 votes
1 answer

How to write a test which expects an Error to be thrown in Jasmine?

Hello @kartik, Try using an anonymous function instead: expect( ...READ MORE

answered Jul 13, 2020 in Node-js by Niroj
• 82,840 points
9,802 views
0 votes
1 answer

How to add tooltip to div in react?

You can utilize React's state management to ...READ MORE

answered Dec 24, 2024 in Node-js by Navya
88 views
0 votes
1 answer

How to add popper.js in React?

Install Popper.js via npm (npm install @popperjs/core), ...READ MORE

answered Feb 23 in Node-js by Kavya
187 views
0 votes
1 answer

How do I redirect to a previous page in react?

You can use the useNavigate hook from ...READ MORE

answered Dec 31, 2024 in Node-js by Navya
102 views
0 votes
1 answer

How to use async functions effectively in React components?

To use async functions effectively in React ...READ MORE

answered Mar 12 in Node-js by Sahil
60 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How does Babel differ from JSX?

Feature Babel JSX Definition A JavaScript compiler that transforms ES6+ code ...READ MORE

answered Mar 12 in Java-Script by Sahil
95 views
0 votes
1 answer

How to declare an array in TypeScript?

In TypeScript, arrays can be declared in ...READ MORE

answered Dec 17, 2024 in Node-js by Navya
108 views
0 votes
1 answer

How to Handle Jest Unit Testing for 'ɵcmp' in a React-in-Angular Hybrid App?

Encountering the 'ɵcmp' property error during Jest ...READ MORE

answered Dec 23, 2024 in Node-js by Navya
109 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP