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

232
Vistas
How to pass copy of object in React useState Initial State

What I am trying to achieve is after fitlerRequest function called filterListValue should manipulate.

But what happening is on radioHandleChange it's start manipulating the filterListValue.

I think they have the same memory reference but how to make a copy of it?

export default function CustomFilter(props) {
    const { filterListValue, setFilterListValue } = props;
const [radioValue, setRadioValue] = useState(filterListValue)

const radioHandleChange = (e, list) => {
        setRadioValue(radioValue => {
            let copy = [...radioValue]
            copy[indexChange].value = e.target.value
            copy[indexChange].id = list.id
            return copy
        });
}

const filterRequest = () => {
        setFilterListValue(radioValue)
        handleClose()
    };

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

0

Just make copies using .... Although not mentioned, looks like props.filterListValue is an array. So create a copy when starting with useState hook. Also, when setting radio value, make a copy of the item (since it is an object) so you are not mutating the state by mistake.

    const { filterListValue, setFilterListValue } = props;
const [radioValue, setRadioValue] = useState([...props.filterListValue])

const radioHandleChange = (e, list) => {
        setRadioValue(radioValue => {
            let copy = [...radioValue]
            let copyItem = {...copy[indexChange]}; 
            copyItem[indexChange].value = e.target.value
            copyItem[indexChange].id = list.id
            return copyItem
        });
}

PS:

You can destructure inside the function argument parenthesis. It is common practice:

export default function CustomFilter({filterListValue, setFilterListValue}) {
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