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.
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 = [];