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

174
Vistas
Do I need to clone props before using/mutating it in React?

Imagine a component has props and the props have nested objects and arrays. In the child component, if I need to copy to props.nestedObject or props.myArrays to state. Is shallow copy OK?

const [obj, setObj] = useState(props.nestedObject)

Or deep copy?

const [obj, setObj] = useState(_.cloneDeep(props.nestedObject))

The reason why I am asking this is that, normally, I use cloneDeep or Immutable.js to not worry about object references. But I don't know whether React does something behind the scenes to break object reference.

PS: _.cloneDeep is a lodash function.

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

react doesn't break object reference. here is an example:

stackblitz.com playground example

I used Object.is() to compare the original object and the object returned from the useState() hook. As you can see, these objects are the same, so react does't apply any kind of cloning

about 4 years ago · Santiago Trujillo Denunciar

0

You can set up an initial state for the useState hook without it being updated

const [obj, setObj] = useState(() => props.nestedObject)

That is what you were looking for

about 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