Search code examples
reactjsevent-handlingreact-state-management

How to manage State values when cursor is moving fast over a component in React JS?


I am trying to set state value when cursor is over a component or not.

toggleIcon = () => {
        this.setState({ isMouseOver: !this.state.isMouseOver });
    };

...

<div
     onMouseEnter={() => this.toggleIcon()}
     onMouseLeave={() => this.toggleIcon()}
>
    {isMouseOver ? (
                    <InfoIcon />
                ) : (
                    <NormalIcon />
                )}
</div>

When I move cursor over that component in normal speed, it works well.

But If I move cursor fast, only onMouseEnter event is triggered but not onMouseLeave event. By the way, InfoIcon is not changing to NormalIcon even the cursor is not over that component.

If there's no state management in toggleIcon function,both events are triggered even if cursor is moving fast over the component.

Please teach me what is wrong and how can I fix it. Thanks. :)


Solution

  • You can use :hover effect to change background image.