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

227
Vistas
How can I prevent my array from being overwritten when setting the state?

What I am trying to do: I want to add all elements into my array

Actual result: My array is being overwritten

As seen from my codesandbox, the output should be helloworld, but it is only showing world.

Parent.js

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

import Child from "./Child";

export default function Parent() {
  const [arr, setArr] = useState([]);

  return (
    <div className="App">
      <Child setArr={setArr} />
      {arr}
    </div>
  );
}

Child.js

import { useEffect } from "react";

export default function Child(props) {
  useEffect(() => {
    props.setArr("hello");
    props.setArr("world");
  });
  return (
    <div className="Child">
      <h1>This is child componemnt</h1>
    </div>
  );
}

This is my codesandbox link

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

0

You overwriting your array with a string, the trick is to create a shallow copy of your value and mutate the new copy. and then set the state afterwards:

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

import Child from "./Child";

export default function Parent() {
  const [arr, setArr] = useState([]);

  return (
    <div className="App">
      <Child setArr={setArr} arr={arr} />
      {arr}
    </div>
  );
}

import { useEffect } from "react";

export default function Child(props) {
  useEffect(() => {
    const nextArr = [...props.arr];
    nextArr.push("hello", "world");
    props.setArr(nextArr);
  }, []);
  return (
    <div className="Child">
      <h1>This is child componemnt</h1>
    </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