Abhay SIngh
Abhay SIngh

Reputation: 27

useState() react state variable doesn't re-renders. Any POV?

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

Answers (1)

Adib Sadeghi
Adib Sadeghi

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

Related Questions