React infinite rendering: a choice between mutating state array or not

As title. I shouldn’t mutate state like this based on suggestion in Cannot see updates from child component through parent's callback (case array and push)

So, in, I try to setWords(a new array), but it triggers infinite rendering.

// React.js libraries are added as external scripts in the JS settings of this pen

const { useState, useEffect } = React;

A = () => {
    const [info, setInfo] = useState("Hello world.");
    const [entered, setEntered] = useState('');
    return (
      <input type="text" 
        onKeyUp={(e)=>{if(e.key=='Enter') setEntered(info); }}
      <B enteredTxt={entered}/>

B = (props) => {
const [words,setWords] = useState([]);
  words.length=0;//I should not do this. I should re-assign a new array like setWords()
  setWords(arrayGen());//But when I do this, the react infinite rendering happens!

const arrayGen=()=>{
  return ['This ','is ','hello ', 'world!'];
const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<A />);

Also, what’s the suggested way to remove all items in an array? From Remove all the elements of the array in React JS , Maybe direct mutating is not a good idea? Any advice is welcome.

newArray =;

>Solution :

If you only want to call setWords only when enteredTxt changes, you should use useEffect like this:

useEffect(() => {
}, [props.enteredTxt])

To remove all items you can simply assign a new array:

newArray = [];

Leave a Reply