Using array as react hook useState

I am using array as value of useState

also I need to change only one element and set it as state

const Main = () => {
  const [test, setTest] = useState([1, 2, 3]);

    function TestFunction({state, setState}): JSX.Element {
        return (
          <div
            style={{
              border: '1px solid black', height: '100px', width: '100%', display: ' block',
            }}
            onClick={() => {
              const qwer = state;
              qwer[2] -= 1;
              setState(qwer);
    
              console.log('clicked', state);
            }}
          >{test}
          </div>
        );
      }
    
    return (
        <TestFunction state={test} setState={setTest} />
    );
}

console says that the value “test” has been changed,

But it never rerenders it.

Am I using wrong? If so, I want to ask some solution please.

Thank you very much.

Answer

You are not making a copy of an array with the = operator. Infact you are mutating the state there. Use ... spread operator:

onClick={() => {
              const qwer = [...state];
              qwer[2] -= 1;
              setState(qwer);
    
              console.log('clicked', state);
            }}