'Print one phrase under another one using speech recognition

The recognition should start when I click recHandler button, then the recognized phrase should be printed below. If I click the button again the recognition should be activated and recognized phrase should be printed under the old one, as result I have to have a list of recognized phrases.

The problem is if I run this part of code setMessage([...message, transcript]) inside useEffect() I get infinite loop of re-renders.

If I run it without useEffect(), I get an error: Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

import React, { useState, useEffect } from 'react'    
import React from 'react';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';

const Dictaphone = () => {
  const {
    transcript,
    listening,
    resetTranscript,
    browserSupportsSpeechRecognition
  } = useSpeechRecognition();

  const [message, setMessage] = useState([])

  const item = (
    <ul>
      {message?.map((n) => (
        <li>{n}</li>
      ))}
    </ul>
  )
    
      if (!browserSupportsSpeechRecognition) {
        return <span>Browser doesn't support speech recognition.</span>;
      }

    function recHandler(){
    SpeechRecognition.startListening()
    }

  useEffect(()=>{
    setMessage([...message, transcript])
  })

  return (
    <div>
      <p>Microphone: {listening ? 'on' : 'off'}</p>
      <button onClick={recHandler}>Start</button>
      <div>{item}</div>
    </div>
  );
};


Solution 1:[1]

Your useEffect cause re-render, you are missing []

useEffect(()=>{
    setMessage([...message, transcript])
  },[transcript])

Sources

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

Source: Stack Overflow

Solution Source
Solution 1