Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda