'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}
/>
Solution 1:[1]
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}
/>)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shahriar Shojib |
