Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 https://codepen.io/jadecubes/pen/dygjGZL, 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" 
        onChange={(e)=>{setInfo(e.target.value);}}
        onKeyUp={(e)=>{if(e.key=='Enter') setEntered(info); }}
        />
      <B enteredTxt={entered}/>
            <h1>{info}</h1>
        </>
    );
};

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

newArray = this.state.data.slice();

>Solution :

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

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

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

newArray = [];

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading