'Remove rendered data from UI

I have a component that prints 10 numbers one after another. I also have a button Clean that have to remove this 10 numbers when it's clicked. I am not sure how to implement it.

import { useState } from 'react'

export default function Timeout() {
  const [message, setMessage] = useState([1])
  const Markup = (
    <ul>
      {message?.map((n) => (
        <li>{n}</li>
      ))}
    </ul>
  )
  setTimeout(() => {
    if (message.length <= 9) {
      setMessage([...message, message[message.length - 1] + 1])
    }
  }, 1000)

  return (
    <div>
      <button>Clean</button>
      <div>{Markup}</div>
    </div>
  )
}

If I add <button onClick={setMessage([])>Clean</button> I get Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source