In the example, you are mutating the original array. The push method mutates the original array.
The reason why your example is working is that when you call updateComp, react triggers a re-render because there is a state change and thus your UI reflecting the changes to the array.
What you need to before updating an array is to make a copy of it so that you don't modify the original array. Then you can push/remove items in the clonedArray. and then you use the setValue method to update the value state. I reflected this in the code below using your example.
importReact,{useState}from"react";import"./styles.css";functionDisplayComp(props={}){// const [updateComp, doUpdateComp] = useState(false);constinitialState=props.data;// that instantiation causes props to mutate// const initialState = [...props.data]; // that instantiation keeps props cleanconst[value,setValue]=useState(initialState);consthandleClick=()=>{constvalueClone=[...value];valueClone.push((value[value.length-1]||1)*2);setValue(valueClone)// doUpdateComp(!updateComp); // that line causes component to re-render};return(<divclassName="App"><h1>ReactHooksstatemanagement</h1>
<buttononClick={handleClick}>Mutate</button>
<p>Initialstatevalue:{initialState.join("")}</p>
<p>usestatevalue:{value.join("")}</p>
</div>
);}exportdefaultfunctionApp(){return<DisplayCompdata={[21]}/>;
}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
In the example, you are mutating the original array. The push method mutates the original array.
The reason why your example is working is that when you call
updateComp
, react triggers a re-render because there is a state change and thus your UI reflecting the changes to the array.What you need to before updating an array is to make a copy of it so that you don't modify the original array. Then you can push/remove items in the clonedArray. and then you use the
setValue
method to update thevalue
state. I reflected this in the code below using your example.