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

130
Vistas
React useState variable doesn't get copied by value

I have a very basic example and I can't figure out what I'm doing wrong. I have a very simple counter and I want to copy its initial state to another variable without the reactivity but can't do so.

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [number, setNumber] = useState({ val: 10 });
  const numberAssign = Object.assign({}, number);
  const numberJSON = { ...number };
  const numberSpread = JSON.parse(JSON.stringify(number));
  const clicked = () => {
    setNumber({ val: number.val + 1 });
  };

  return (
    <div className="App">
      <button onClick={clicked}>Inc</button>
      <p>{number.val}</p>
      <p>{numberAssign.val}</p>
      <p>{numberJSON.val}</p>
      <p>{numberSpread.val}</p>
    </div>
  );
}

All of the variables get incremented when clicking the button but I want only the number variable to increment.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The variables are not behaving abnormally. You are setting the variables to the value of the state variable which in this case is constantly being updated. Try having the val variable declared outside of the state

`const val = 10;
const [number, setNumber] = useState({ val });`

then use val instead of the number state.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I don't know if that is going to help you a lot, but you can use another useState hook where you gonna store the prev value of the current state. Code:

import { useState } from "react";

export default function App() {
  const [currNum, setCurrNum] = useState(10);
  const [prevNum, setPrevNum] = useState(0);
  const clicked = () => {
    setPrevNum(prevNum);
    setCurrNum(prevNum+=1);
  };
  return (
    <div className="App">
      <button onClick={clicked}>Inc</button>
      <p>{currNum}</p>
      <p>{prevNum}</p>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

On every setState(useState) action the component will rerender everything inside it. It will only keep the values which created using react hooks such as useState (That is what useState wants to do)

Put a console.log('rerender') just before all useStates you will see it will trigger on its very action, that means in functional components it are will not keep any variables or values unless it is created using react hooks, even if it is const variable

In you case this const variables are created again and assigned new number object to it that's why it is getting updated every time. but you can use it in different useStates, or you can define it inside a useEffect wich will trigger only calls in specific times import { useState } from "react";

export default function App() {
  console.log('rerender')
  const [number, setNumber] = useState({ val: 10 });
  const [numberAssign, setN] = useState(Object.assign({}, number));
  const [numberJSON, setJSON] = useState({ ...number });
  const [numberSpread,setSpread] = useState(JSON.parse(JSON.stringify(number)));
  const clicked = () => {
    setNumber({ val: number.val + 1 });
  };

  return (
    <div className="App">
      <button onClick={clicked}>Inc</button>
      <p>{number.val}</p>
      <p>{numberAssign.val}</p>
      <p>{numberJSON.val}</p>
      <p>{numberSpread.val}</p>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza 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