Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda