Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
React functional components, setState and immutability

Feeling a little dumb, I've been working with React for 2 years and always thought that you have to use setState with a new copy of the object to avoid mutating the state. However, this example mutates the state and uses setState with the same object reference without any issue.

Why does this work?

Working Code Pen

const { useState } = React;

const Counter = () => {
  const [countObject, setCountObject] = useState({count: 0});

  const onClick = () => {
    countObject.count = countObject.count + 1;
    setCountObject(countObject); // mutated object, same reference
    
  }
  
  return (
    <div>
      <p>You clicked {countObject.count} times</p>
      <button onClick={onClick}>
        Click me
      </button>
    </div>
  )
}

ReactDOM.render(<Counter />, document.getElementById('app'))
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Immutability is very important of course, your code works, just because modify the original object doestn't affect functions. Change the code by sharing initial value, then click arbitary button, you will find something wrong.

const { useState } = React;

const Counter = () => {
  const value = { count: 0 }
  const [countObject, setCountObject] = useState(value);
  const [countObject2, setCountObject2] = useState(value);

  const onClick = () => {
    countObject.count = countObject.count + 1;
    setCountObject(countObject);
  }
  
  const onClick2 = () => {
    countObject2.count = countObject2.count + 1;
    setCountObject(countObject2);
  }
  
  return (
    <div>
      <p>You clicked {countObject.count} times</p>
      <button onClick={onClick}>
        Click me
      </button>

      <p>You2 clicked {countObject2.count} times</p>
      <button onClick={onClick2}>
        Click me2
      </button>
    </div>
  )
}

ReactDOM.render(<div><Counter /></div>, document.getElementById('app'))
over 4 years ago · Santiago Trujillo Relatório

0

Your codepen is using an alpha version of React 16.7. Hooks were released in 16.8, so to use hooks reliably, you should be using a version 16.8 or above (in a non-alpha version of React):

enter image description here

You can update the version number of both of the above links by clicking the gear icon in your codepen on the JavaScript pane.

Notice the below snippet uses 16.7.0-alpha.2 and has the same issue you were experiencing:

const { useState } = React;

const Counter = () => {
  const [countObject, setCountObject] = useState({count: 0});

  const onClick = () => {
    countObject.count = countObject.count + 1;
    setCountObject(countObject);
  }
  
  return (
    <div>
      <p>You clicked {countObject.count} times</p>
      <button onClick={onClick}>
        Click me
      </button>
    </div>
  )
}

ReactDOM.render(<Counter />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0-alpha.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script>
<div id="app"></div>

However, changing your version to 16.8 or later fixes the issue (as of writing this, we're up to v17.0.2):

const { useState } = React;

const Counter = () => {
  const [countObject, setCountObject] = useState({count: 0});

  const onClick = () => {
    countObject.count = countObject.count + 1;
    setCountObject(countObject);
  }
  
  return (
    <div>
      <p>You clicked {countObject.count} times</p>
      <button onClick={onClick}>
        Click me
      </button>
    </div>
  )
}

ReactDOM.render(<Counter />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda