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

114
Vistas
React using state array without mutation

Can the below code be refactored so as to not mutate the state array. Basically, I want that as I navigate the app back and forth via props.history.push, it should not recreate the array, as I my aim is to preserve the selected option.

const [options1, setOptions1] = useState([
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2}
]);
const [options2, setOptions2] = useState([
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2},
    {value: 'XYZ', text: 'XYZ', id: 3}
]);

let finalOpts = options1; // Is there a better way to do this ?
if (someConditionIsTrue) {
    finalOpts = options2;
}

const [selectedOpt, setSelectedOpt] = useState(finalOpts[0]);

<MyList
    id="myDD"
    selectedOpt={selectedOpt}
    options={finalOpts}
/>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Use useMemo to precalculate the values if your UI logic depends on some conditional. This alone will not preserve the selectedState if the component is unmounted. In order to preserve the selected state even after the component has been unmounted, you will have to store the selection in some kind of global state.


const options = useMemo(() => {
  if(someConditionIsTrue) {
    return [
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2}
    ];
  }
  return [
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2},
    {value: 'XYZ', text: 'XYZ', id: 3}
]
}, [someConditionIsTrue]);

const [selectedItem, setSelectedItem] = useState();



return (<MyList
    id="myDD"
    selectedOpt={selectedItem || options[0]}
        onSelectionChanged={setSelectedItem}
    options={options}
/>)
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