Q: React - How to show last value of variable depending on condition I have a modal with like this:
const [selectedNumber, setSelectedNumber] = useState(-1);

<Modal open={selectedNumber > 0}>
    <button onClick={() => setSelectedNumber(-1)}>Close</button>
    You selected {selectedNumber}
</Modal>

My problem is, when I close the modal, since the modal has a transition, I can see, for a brief time, the "-1" on the screen.
I know I can use another flag for the open state, but, is there any way to avoid doing this and just getting react to display the last known value if selectedNumber < 0?

A: your question is a bit wired. but here is a way
const [selectedNumber, setSelectedNumber] = useState(-1);
const [lastKnownNumber, setLastKnownNumber] = useState(0);

<Modal open={selectedNumber > 0}>
    <button onClick={() => {
         setLastKnownNumber(selectedNumber); 
         setSelectedNumber(-1);
    }}>
       Close
   </button>
    You selected {selectedNumber>0 ? selectedNumber : lastKnownNumber}
</Modal>


A: No, because if you think about this logically, it won't be possible unless React has a magical "cached" state value that preserves the last state value before any change. And React doesn't have that kind of value stored.
The best way is as you already said using a flag. That's a better practice anyway. Because:
One important thing to understand is the code should be extremely clear to read. Any "smart" solution like yours opens a possibility for misunderstanding and difficulty to understand. More code doesn't necessarily mean worse code.
const [selectedNumber, setSelectedNumber] = useState(-1);
const [isModalVisible, setIsModalVisible] = useState(false);

<Modal open={isModalVisible}>
    <button onClick={() => setIsModalVisible(false)}>Close</button>
    You selected {selectedNumber}
</Modal>

