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

124
Vistas
Unable to update React.useState("") after joining all elements in array to single string

I am trying to update a React.useState("") using setDisplay in a function that takes an array of strings and joined them into a single string before setDisplay.

Without the setDisplay, I'm able to console.log() and get the joined array.

const App = () => {
  const [display, setDisplay] = React.useState("");

  const values = [];
  const onClick = (value) => {
    values.push(value);
    console.log(values) // w/o setDisplay output: ["1","2","3","4"]; w/ setDisplay output: ["1"]; ["2"]; ["3"]; ["4"];
    setDisplay(values.join(""))
  };

  return (
    <div className="p-5">
      {display}
      <NumPads data={keypress} onClick={onClick} />
      <OperatorPads data={keypress} onClick={onClick} />
    </div>
  );
};
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

setDisplay((values) => ([...values, value].join("")]))
about 4 years ago · Juan Pablo Isaza Denunciar

0

  const onClick = (value) => setDisplay((dispay) => display.concat('', value));
about 4 years ago · Juan Pablo Isaza Denunciar

0

The reason the console.log seems to work when you don't call setDisplay is simply because the state of the component did not change.

When you call setDisplay, you change the state, so the entire component re-renders, which causes values to reset back to an empty array.

Solution(s)

  • One way to solve this is already shown in a previous answer.

  • Another way is to wrap your values array with useRef:

    const values = useRef([]);
    

    Then access the array using values.current

  • Yet another way is to eliminate the use of values all together and change the callback to:

    const onClick = (value) => {
      setDisplay(display + value);
    };
    
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