Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!