Reputation: 27
I need some input on React. I have this code block. As per my understanding the after setStateX(copy), the whole component re-renders. But in my case, it's not happening. Any reason for that?
const [stateX, setStateX] = useState([]);
const addAnotherComponent = (e) => {
let copy = stateX;
copy.push(
<AnotherComponent/>
);
setStateX(copy);
};
Upvotes: 0
Views: 130
Reputation: 128
because you mutate the state and the component doesnt re-render you first should clone state let copy=[...stateX]
let updatedState = [...copy,yourcomponent]
setStateX(updatedState)
Upvotes: 1