Add new element to DOM in React

I’m new to React, I try to create add a new element to DOM when onClick. So I play with the state. Like below:

const [number, setNumber] = useState(1);
const [item, setItem] = useState(() => [{id: number,task: `Task ${number}`}]);

const increaseItem = () => {
    setNumber(number + 1)
    console.log(number)
    setItem([...item, {id: number, task: `Task ${number}`}])
    console.log(item)
}

But I got an issue when I push the array in useState, the first element of the array copied twice. Here the result of the array:

4 //result of the number

/* Result of item */
0: {id: 1, task: "Task 1"}
1: {id: 1, task: "Task 1"}
2: {id: 2, task: "Task 2"}
3: {id: 3, task: "Task 3"}

Could you show me how the correct way to solve this. Thank you.

75 thoughts on “Add new element to DOM in React”

  1. Greetings from Colorado! I’m bored to tears at work so I decided to browse your blog on my
    iphone during lunch break. I enjoy the knowledge you present here and can’t wait to take a look when I get home.

    I’m surprised at how fast your blog loaded
    on my cell phone .. I’m not even using WIFI, just 3G ..
    Anyways, excellent blog!

    Reply
  2. Hi there just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Chrome.
    I’m not sure if this is a format issue or something to do with web browser compatibility but I figured
    I’d post to let you know. The design and style look great though!
    Hope you get the issue solved soon. Kudos

    Reply
  3. With havin so much written content do you ever run into
    any issues of plagorism or copyright violation? My blog has a lot of exclusive content
    I’ve either written myself or outsourced but it looks like a lot of it is popping it up all over
    the internet without my agreement. Do you know any techniques to
    help prevent content from being ripped off? I’d genuinely appreciate it.
    scoliosis surgery https://coub.com/stories/962966-scoliosis-surgery scoliosis surgery

    Reply

Leave a Comment