'Comparing two values from Dropdown

I have a Dropdown from which I pass the Name value OnClick

onClick={() => clicked(v.Name)

Then, in the clicked event I want to compare that the input value is not the same as old value but this fails because I cannot update oldName after comparing the values. Probably there is a better logic to this. I also tried UseEffect and UseState but they tended to update with previous values.

function DropdownComponent() {

    var oldName;

    function clicked(Name) {
        if (Name === oldName) {
            console.log("Same Clicked!");
        }
        else {
            console.log("Differet Clicked!");
            setTitleName(Name)
        } return oldName = (Name); //can't update
    }

    return (
    <Dropdown //dropdown component

}


Solution 1:[1]

Anything stored in a component-local variable only exists for that render. Each render will re-declare the variable. So this variable:

var oldName;

Will always be undefined on every render. Component-local variables can be useful for temporary storage. For example, you can perform sorting/filtering logic on an array and store the results in variables for the purpose of mapping those variable to UI components in the render, effectively separate the sorting/filtering logic from the rendering logic.

But those variable do not persist across renders.

If you want something to be retained across renders, you want to keep it in state. Which you appear to already be doing here:

setTitleName(Name)

The code shown doesn't include this, but presumably somewhere you're creating a state value like this?:

const [titleName, setTitleName] = useState('');

If we are to assume that this "title name" is a state value then you already have the "previous value", it's the one you're keeping in state. So just check against that one:

function clicked(name) {
    if (name === titleName) {
        console.log("Same Clicked!");
    } else {
        console.log("Differet Clicked!");
        setTitleName(name);
    }
}

Live demo

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 David